CodesJava

Easy learning with example program codes

Java reflection instantiate an object


The java.lang.Class provides the methods to examine the runtime properties of the object including its members and type information. For every type of object, the JVM instantiates an immutable instance of java.lang.Class. Using reflection, we can get the metadata of a class at run time.

The newInstance() method on constructor object is used to instantiate a new instance of the class.

Example

TestClass.java

package com.codesjava;
 
public class TestClass {
	private String message;
 
	public TestClass(String message){
		this.message = message;
	}
 
	public void display(){
		System.out.println(message);
	}
}

ReflectionTest.java

package com.codesjava;
 
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
 
public class ReflectionTest {
	public static void main(String args[]){
		try {
			Class c=Class.forName("com.codesjava.TestClass");  
			Constructor<?> constructor = c.getConstructor(String.class);
			Object testObject = constructor.newInstance("codesjava.com");
			Method myObjMethod = testObject.getClass().getMethod("display", null);
			myObjMethod.invoke(testObject, null);
		} catch (Exception e) {
			e.printStackTrace();
		}  
	}
}

Output

codesjava.com


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap