Java記錄 -86- Reflection API的使用樣本進階2
擷取指定類下的資訊:所有方法和屬性
public class DumpClassInfo { public static void main(String[] args) throws Exception{ //Reflection API的基本作用 Class<?> classtype = Class.forName("my.reflect.Customer"); Method[] methods = classtype.getDeclaredMethods(); //擷取指定類下的所有方法,包含私人方法。(運行時所有方法) for(Method method : methods){ System.out.println(method); } Field[] fields = classtype.getDeclaredFields(); //擷取指定類下的所有屬性,包含私人屬性。(運行時所有屬性) for(Field field : fields){ System.out.println(field); } }}class Customer{ private long id; private String name; private int age; public Customer(){} public Customer(String name, int age){ this.name = name; this.age = age; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }}
以上程式輸出結果:
public void my.reflect.Customer.setId(long)public int my.reflect.Customer.getAge()public void my.reflect.Customer.setAge(int)public java.lang.String my.reflect.Customer.getName()public long my.reflect.Customer.getId()public void my.reflect.Customer.setName(java.lang.String)private long my.reflect.Customer.idprivate java.lang.String my.reflect.Customer.nameprivate int my.reflect.Customer.age