Home  >  Core Java

Example of Modifier in Reflection API in java

By Arvind Rai, January 20, 2013
Modifier class belongs to the package java.lang.reflect. Modifier checks whether the method or variable is private, protected, and public and is static, abstract, native, strict etc. And it also checks for class to be interface or class or abstract. It gives all information of a class. Modifier has static fields and static methods to handle the above scenario. Like if a class contains static method, it gives information about that static method.
package com.concretepage.reflection;

public class TestClass {
	
	private String name;
	private int age;
	public TestClass(String s,int a){
		this.name=s;
		this.age=a;
	}
	public String getName() {
		return name;
	}
	public int getAge() {
		return age;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	private  void show(){
		System.out.println("hello");
	}
}
package com.concretepage.reflection;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class ReflectionModifierTest {
    public static void main(String... args) throws ClassNotFoundException{
    	Class<?> c= Class.forName("com.concretepage.reflection.TestClass");
    	//gets all methods
    	Method[] m=c.getDeclaredMethods();
    	for(int i=0;i< m.length;i++){ 
    		//checks the method to be public
    		if(Modifier.isPublic(m[i].getModifiers())){
    			System.out.println(m[i].getName()+" is public.");
    		}
    		//checks the method to be static
    		else if(Modifier.isPrivate(m[i].getModifiers())){
    			System.out.println(m[i].getName()+" is private.");
    		}
    	}
    	
    }
}
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us