public Class<Example> getExampleByInstance(){
Example example = new Example();
// getClass是Object類裡面的方法;《?》 是通配符
Class<?> clazz = example.getClass();
return (Class<Example>)clazz;
}
//獲取所有的構造方法 / private public
public Constructor<?>[] getDeclaredConstructors()
//獲取特定的構造方法 / private public
public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
//獲取類的父類
public native Class<? super T> getSuperclass()
//獲取類實現的介面
private Class<?>[] getInterfaces(boolean cloneArray)
//獲取在類內定義的內部類或介面
public Class<?>[] getDeclaredClasses()
//獲取所有的方法
public Method[] getDeclaredMethods() throws SecurityException
//根據方法名和參數獲得特定的方法
public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
//獲取類型的定義的所有屬性
public Field[] getFields() throws SecurityException
// 根據屬性命名獲得特定的Field
public Field getField(String name)
Method常用的操作方法
//獲得方法的放回類型
public Class<?> getReturnType()
//獲得方法的傳入參數類型
public Class<?>[] getParameterTypes()
//obj是實例對象,args是方法,反過來由Method控制對象的方法調用
public Object invoke(Object obj, Object... args)
Field常用的操作方法
//屬性與obj相等則返回true
public boolean equals(Object obj)
//獲得obj中對應的屬性值
public Object get(Object obj)
//設置obj中對應屬性值
public void set(Object obj, Object value)
Constructor
//根據傳遞的參數創建類的對象:initargs 構造方法參數
public T newInstance(Object... initargs)
1根據class創建對象
//方式一 clazz.newInstance()
Class<Example> clazz = Example.class;
Example example = clazz.newInstance();
//方式二 先獲取再由Constructor:clazz.getConstructors()/getConstructor(...)
//再由Constructor.newInstance 方法構造對象
-----------------------------------------
public class Example {
private int value;
public Example(){ } // 如果只聲明有參構造函數,clazz.newInstance()會報錯
public Example(Integer value){ this.value = value; }
static public void main(String[] args) throws Exception{
Class<Example> clazz = Example.class;
//根據指定構造函數參數獲取Constructor
Constructor<Example> constructor = clazz.getConstructor(Integer.class);
Example example = constructor.newInstance(100);
System.out.println(example.value);
}
}
2由class獲取Field,並操作實例的屬性
public class Example {
private int value , count;
static public void main(String[] args) throws Exception{
Class<Example> clazz = Example.class;
//獲取所有的屬性,getField只能獲取public的屬性
Field[] fs = clazz.getDeclaredFields();
//根據名稱獲取指定 Field
Field value = clazz.getDeclaredField("value");
Example example = clazz.newInstance();
//使用反射機制可以打破封裝性,導致了java對象的屬性不安全
value.setAccessible(true); //setAccessible(true)讓private的參數可賦值操作
//由Field反過去設置example的值
value.set(example,100);
System.out.println(example.value);
}
}
3由class獲取Method,並反射調用實例方法
public class Example {
public static void main(String[] args) throws Exception {
Class<Example> clazz = Example.class;
Example example = clazz.newInstance();
Method[] methods = clazz.getDeclaredMethods();
//getDeclaredMethod和getMethod是:getMethod只能返回public的方法
Method method = clazz.getDeclaredMethod("hello", String.class);
method.setAccessible(true);
method.invoke(example, "cscw");
}
private void hello(String name) { System.out.println(name + " Hello!"); }
}
-----
cscw Hello!