標籤:blog row 擷取 sts out tty res read ddr
package com.lf.testreflection;import java.lang.reflect.Field;import java.lang.reflect.Method;import org.junit.Test;public class ClassTest{ @Test public void testSomthing()throws Exception { //建立運行時類的對象 Class cla = Person.class; // 建立運行時Person的對象 Person person = (Person)cla.newInstance(); // 通過cla擷取對象的屬性 Field field = cla.getDeclaredField("name"); // 設定可以訪問的許可權 field.setAccessible(true); // 設定相應的屬性值 field.set(person, "kity"); //擷取相應的屬性(public可以使用下面方法擷取) field = cla.getField("address"); field.set(person, "NewYo"); field = cla.getDeclaredField("age"); field.setAccessible(true); field.set(person, 18); System.out.println(person); // 擷取無參方法 Method method = cla.getMethod("learn"); method.invoke(person); // 擷取有參方法 Method method2 =cla.getMethod("readSomething",String.class); method2.invoke(person, "ainsy"); // 擷取多參方法 Method method3 =cla.getMethod("readSomething",int.class,String.class); method3.invoke(person, 20,"ainsy"); // 擷取所有的屬性 Field[] fields = cla.getDeclaredFields(); for (Field field2 : fields) { // 每個屬性的修飾符 System.out.print(field2.getModifiers()+" "); // 每個屬性名稱 System.out.print(field2.getName()+" "); // 擷取屬性的類型 Class type = field2.getType(); System.out.println(type); } // 調用運行時本身的.class屬性 Class cla2 = Person.class; //列印類路徑 System.out.println(cla2.getName()); // 通過運行時類的對象擷取 Person p = new Person(); Class cla3 = p.getClass(); System.out.println(cla3.getName()); }}
Java 反射的基本應用