Two forms of instantiating an object:
1) through the keyword new
2) Complete by reflection mechanism
Packagetest;//Book classclassBook {PrivateString title; Private DoublePrice ; Public voidSetpric (DoublePrice ) { This. Price =Price ; } Public voidSettitle (String title) { This. title =title; } @Override PublicString toString () {return"Book Name:" + title + "Price:" +Price ; }} Public classtestreflection { Public Static voidMain (string[] args)throwsException {Class<?> cls = Class.forName ("test. Book"); package name. Class name book book=(book) CLS. newinstance (); Book.settitle ("Java"); Book.setpric (10.01); System.out.println (Book.tostring ()); Book Name: Java Price: 10.01 }}
Q: If no parameter construction method is provided in the class, only the parameter constructor method is provided, you must explicitly invoke the specified construction method to instantiate the object by reflection
Packagetest;ImportJava.lang.reflect.Constructor;//Book classclassBook {PrivateString title; Private DoublePrice ; PublicBook (String title,DoublePrice ) { This. Price =Price ; This. title =title; } @Override PublicString toString () {return"Book Name:" + title + "Price:" +Price ; }} Public classtestreflection { Public Static voidMain (string[] args)throwsException {Class<?> cls = Class.forName ("Test. Book "); Constructor <?> cons = Cls.getconstructor (String.class,double.class); Book Book= (book)cons.newinstance ("Java", 10.01); System.out.println (Book.tostring ()); //Book Name: Java Price: 10.01 }}
Java--Reflection mechanism