- Test entity classes
public class TestClass {public String ClassInfo; Public String GetClassInfo () { return classinfo; } Public TestClass (String classinfo) { this.classinfo = ClassInfo; System.out.println ("Invoke this Param ClassInfo constructor."); Public TestClass () { System.out.println ("Invoke this default constructor."); public void Setclassinfo (String classinfo) { this.classinfo = ClassInfo; } static { System.out.println ("Init first class."); } public void Showinfo () { System.out.println ("This is the default Show info method.") ; public void Showinfo (String info) { System.out.println ("This is has Param method."); System.out.println ("param context:" +info);} }
- Testing the Implementation class
Import Org.junit.test;import Java.lang.reflect.constructor;import Java.lang.reflect.field;import Java.lang.reflect.method;public class Getclassinfotest {@Test public void Testdemo () throws Exception {/ * * 1. The first step in implementing reflection: Gets the type information of the object, and Java refers to the. class file that holds the type information * 2. Here is all the constructor methods for getting the object. * 3. Find the required construction method. * 4. Call the specified construction method to create the object. */Class Clazz=class.forname ("TestClass"); /** * Get Construction method * Call Newinstance (...) equivalent to new TestClass (...) */constructor[] constructors=clazz.getconstructors (); System.out.println ("Constructor Item:" + ' \ n '); Arraytostringitem (constructors); Object test=constructors[0].newinstance (); Object test2=constructors[1].newinstance ("Hello"); /** * Get Properties */field[] fields=clazz.getfields (); System.out.println ("Field item:" + ' \ n '); Arraytostringitem (fields); Field Field=fields[0]; System.out.println ("Field name:" +field.geTname ()); System.out.println ("Get Dafault constructor field value:" +field.get (test)); System.out.println ("Get has Param constructor field value:" +field.get (test2)); /** * Acquisition Method */method[] methods=clazz.getmethods (); System.out.println ("Method Item:" + ' \ n '); Arraytostringitem (methods); System.out.println ("Invoke" +methods[0].getname () + "Get Return Value:" +methods[0].invoke (test2)); } public void Arraytostringitem (object[] args) {for (Object C:args) {System.out.println (c ); } }}
Java Reflection Common Classes