Home  >  Core Java

Example of Method in Reflection API in Java

By Arvind Rai, January 18, 2013
Reflection API provides a Method class. At run time we can access the methods and can invoke. Create the class with forName method and call getDeclaredmethods. This will return Method object. With the method object, we can invoke the method by passing the arguments. We can set and get the values from the Method class.
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;
	}
}
package com.concretepage.reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;

public class ReflectionMethodTest {
	public static void main(String... args) throws ClassNotFoundException, SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException{
		Class<?> c= Class.forName("com.concretepage.reflection.TestClass");
		
		//gets the methods
		Method[] method=c.getDeclaredMethods();
		for(Method m:method){
			//prints method name
			System.out.println(m.getName());
			//returns method return type
			Type t=m.getGenericReturnType();
			System.out.println(t);	    
		}
		Method m=c.getDeclaredMethod("setName",String.class);
		m.invoke(c.newInstance(),"Atul");
	}
}
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us