This program shows how to Get Constructor of a class you don't know about and Call it in Java.
AnotherClass.java
public class AnotherClass { public AnotherClass(int no) { x = no; System.out.println("Constructor of Another Class called and the value of x is " + x); } public int x; public int getX() { return x; } }
MainClass.java
import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; /** * Get Class name in Java - Reflection API * * How to get class name when you don't know what the class is in Java */ public class MainClass { public static void main(String[] args){ AnotherClass obj = new AnotherClass(1); // setting value of x = 1 Class c = obj.getClass(); Constructor[] constructorArray = c.getConstructors(); // Returns array of all constructors of AnotherClass System.out.println("Constructors of " + c.getName() + " class are " + constructorArray.length); //Get the constructor from the constructorArray Constructor constructor = constructorArray[0]; //since we don't know about the data type of obj so we'll create an object's object Object object = null; try {
//Invoke Constructorobject = constructor.newInstance(10);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
No comments:
Post a Comment