public Class<Example>getExampleByInstance(){
Example example =newExample();// getClass是Object類裡面的方法;《?》 是萬用字元
Class<?> clazz = example.getClass();return(Class<Example>)clazz;}
//屬性與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 方法構造物件-----------------------------------------publicclassExample{privateint value;publicExample(){}// 如果只宣告有參建構函式,clazz.newInstance()會報錯publicExample(Integer value){this.value = value;}staticpublicvoidmain(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,並操作範例的屬性
publicclassExample{privateint value , count;staticpublicvoidmain(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);}}