1 Packagereflection;2 3 Public classTest Reflection {4 Public Static voidMain (string[] args) {5System.out.println (Runtime.getruntime (). GetClass ());//class Java.lang.Runtime6Test Reflection t=Newtest Reflection ();7System.out.println (T.getclass ());//class reflection. Test Reflection8 }9}GetClass
1 Packagereflection;2 3 Public classTest Reflection {4 Public Static voidMain (string[] args) {5Test Reflection t=Newtest Reflection ();6 //The class is the source of the reflection operation, and all reflections begin from this class. 7Class<?> Cls=t.getclass ();//the 1th class instantiation method is seldom used8SYSTEM.OUT.PRINTLN (CLS);//class reflection. Test Reflection9Class<?> cls2=test Reflex.class;//the 2nd Class instantiation method, using many, fields of use: Hibernate, Mybatis, SpringTenSystem.out.println (CLS2);//class reflection. Test Reflection OneClass<?> cls3=NULL; A Try { -Cls3=class.forname ("Reflection. Test reflection ");//the 3rd Class instantiation method is used more. Here to write the full name, that is, add the package name, or error. -}Catch(ClassNotFoundException e) { the e.printstacktrace (); - } -System.out.println (CLS3);//class reflection. Test Reflection - } +}3 Instantiation of class classes
1 Packagereflection;2 classa{3 PublicA () {4SYSTEM.OUT.PRINTLN ("Call the parameterless construct to instantiate the object.") ");5 }6 @Override7 PublicString toString () {8 returnCall the ToString () method. ";9 }Ten } One Public classTest Reflection { A Public Static voidMain (string[] args) { -Class<?> cls=NULL; - Try { theCls=class.forname ("Reflection. A); -}Catch(ClassNotFoundException e) { - e.printstacktrace (); - } +Object o=NULL; - Try { +o=cls.newinstance (); A}Catch(instantiationexception e) { at e.printstacktrace (); -}Catch(illegalaccessexception e) { - e.printstacktrace (); - } - System.out.println (o); - /** in * Operation Result: - * Call the parameterless construct instantiation object. to * Call the ToString () method. + */ - } the}instantiating an object with reflection
Simple example of "Java" reflection