[JavaSE] reflection-Class usage, javase-class
JAVA-Reflect
① Use of Class
② Reflection of methods
③ Reflection of member variables
④ Reflection of Constructor
⑤ Java class loading mechanism
I. In an object-oriented world, everything is an object
A Class is an object, and a Class is an instance object of the java. lang. Class.
There are three Representation Methods for instance objects of Class II.
// The first expression (known class name)
// Second expression (known object)
// The third expression (by the full name of the Class)
Package com. tsh. reflect; public class ReflectDemo {public static void main (String [] args) {Foo foo1 = new Foo (); // Instance Object of the Class // first expression (known Class name) Class c1 = Foo. class; // second expression (known object) Class c2 = foo1.getClass (); // third expression (by Class name) class c3 = null; try {c3 = Class. forName ("com. tsh. reflect. foo ");} catch (ClassNotFoundException e) {e. printStackTrace ();} // explanation on the official website: c1 and c2 indicate the class type of the Foo Class. // a class can only be an object of the Class, therefore, the output below is true System. out. println (c1 = c2); // you can create an instance object for this class through the class type of the class. try {// The constructor for this class that requires no parameters: Foo foo2 = (Foo) c1.newInstance (); foo2.print ();} catch (InstantiationException e) {e. printStackTrace ();} catch (IllegalAccessException e) {e. printStackTrace () ;}} class Foo {void print () {System. out. println ("test ");}}