Home  >  Core Java

Example of Constructor in Reflection API in Java

By Arvind Rai, January 16, 2013
Constructor in Reflection API fetches the constructor of a class at runtime. The method getConstructor returns the Constructor class of reflection API. The constructor class has the method newInstance. It takes the values for constructor arguments and returns the object of the class. This will be a normal object and can be used to fetch methods and variable. The method getGenericParameter returns the Type class and can be used to the argument names.
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;
	}
}
package com.concretepage.reflection;

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

public class ReflectionConstructorTest {
	public static void main(String... args) throws NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException{
		Constructor<TestClass> c= TestClass.class.getConstructor(String.class,int.class);
		TestClass  mo = (TestClass)c.newInstance("Atul",20);
		//fetch method
		System.out.println(mo.getName());
		
		//fetch method
		System.out.println(mo.getAge());
		
		//gets modifiers
		System.out.println(c.getModifiers());
		
		//get length of parameter types
		System.out.println(c.getParameterTypes().length);
		
		//gets class name
		System.out.println(c.getName());
		
		//gets the name of arguments
		Type[] tp= c.getGenericParameterTypes();
		for(Type t:tp){
			System.out.println(t.getClass().getName());
		}

	}

}
Output:
Atul
20
1
2
com.concretepage.reflection.TestClass
java.lang.Class
java.lang.Class
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us