- Reference material
- Java core technology Volume 1
- java provides a very rich library for reflection
- Purpose of reflection
- Dynamic operation Java code program
- Analysis class in operation
- Querying objects at run time
- Implementation of general array operation code
- Using the method object
- The reflection mechanism is powerful and complex, which is used by program builders. Good use can also be used to analyze the java underlying layer.
- Class Class
- Class is a subclass of Object, but it is not an Object. It is a type. It's not an Object concept like a basic type.
- The Object class directly calls getClass and returns an instance of Class type
- Code example
-
//If the class path or name is wrong, it will explode and no such exception can be found // String className = "java.util.DateNONONONO"; // java.lang.ClassNotFoundException: java.util.Datenonono // at java.net.URLClassLoader.findClass(URLClassLoader.java:381) // at java.lang.ClassLoader.loadClass(ClassLoader.java:424) // at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338) // at java.lang.ClassLoader.loadClass(ClassLoader.java:357) // at java.lang.Class.forName0(Native Method) // at java.lang.Class.forName(Class.java:264) // at com.testservice.Demo001.main(Demo001.java:13) //Date class String className = "java.util.Date"; try { //Generate a mine based on the package name class name Class<?> dataClass = Class.forName(className); //Print the name of the Date System.out.println("dataClass.getName() = " + dataClass.getName()); //Output dataClass.getName() = java.util.Date //Call the api of Class to create a default construction instance of this object Object obj = dataClass.newInstance(); //Forced conversion to date Date dateObj = (Date) obj; //Call the method output to see if it works long time = dateObj.getTime(); System.out.println("time = " + time); //Output time = 1536371161364 System.out.println(dataClass.getName() + ">>" + dataClass.getClass().getName()); //Output Java. Util. Date > > java. Lang.class } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); }
-
- Purpose of reflection
To write TODO