Java中反射技術的例項
阿新 • • 發佈:2018-11-30
準備一個實體類:
package test.reflect; /** * 反射使用的實體類 * * @author liulei on 2018/11/28 */ public class User { //欄位 private String username; private String pwd; private String uid="1001"; //構造方法 public User(){ } public User(String username){ this.username=username; } public User(String username,String pwd){ this.username=username; this.pwd=pwd; } //例項方法 public void function1(){ System.out.println("function1"); } public void function2(String username){ System.out.println("function2"); } public String function3(String username,String pwd){ System.out.println("function3"); return username; } public String getUid(){ return uid; } }
測試類:
package test.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * 反射的測試類 * * @author liulei on 2018/11/28 */ public class ReflectDemo { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchFieldException { //獲取一個類物件 Class<?> c = Class.forName("test.reflect.User"); //獲取一個無引數的構造器 Constructor<?> constructor = c.getConstructor(); //利用構造方法建立物件 Object o = constructor.newInstance(); //因為欄位是私有的,所以不能這樣獲取 // Field field = c.getField(null);Field[] declaredFields = c.getDeclaredFields(); //迴圈輸出欄位 for(int i=0;i<declaredFields.length;i++){ //設定私有欄位可以訪問,如果不設定這一步,就會報private錯誤 declaredFields[i].setAccessible(true); System.out.println("ziduan:"+declaredFields[i].getName()); // System.out.println(declaredFields[i].toString()); } //獲取構造方法 System.out.println(c.getDeclaredConstructor(null)); System.out.println(c.getConstructor(String.class)); System.out.println(c.getConstructor(String.class,String.class)); //獲取例項方法的名稱 System.out.println(c.getMethod("function1").getName()); System.out.println(c.getMethod("function2", String.class).getName()); System.out.println(c.getMethod("function3", String.class, String.class).getName()); //method和invoke;invoke是呼叫例項方法 Method function1 = c.getDeclaredMethod("function1"); function1.invoke(o); //獲取實體類中的常量值 Method id= c.getDeclaredMethod("getUid"); //invoke方法是對有引數的方法進行呼叫 Object invoke = id.invoke(o); System.out.println(invoke); Method function3 = c.getDeclaredMethod("function3", String.class, String.class); String name=function3.invoke(o,"zhangsan","lisi").toString(); System.out.println("1111111111"); System.out.println(name); } }