Java:反射的常用用法,

來源:互聯網
上載者:User

標籤:hash   source   add   method   amt   賦值   win   over   load   

常用反射方法:

package reflection;import java.io.IOException;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.net.URL;public class testReflection {    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {        String str="reflection.T";        //擷取類        Class c=Class.forName(str);        //擷取類路徑        URL z=c.getResource("");        URL s=c.getClassLoader().getResource("");        //得到class在類中的地址        ClassLoader d=c.getClassLoader();        //得到class,c所實現的介面Class[] f=c.getInterfaces()[0];        Class[] f=c.getInterfaces();        System.out.println(z);        System.out.println(s);        System.out.println(d);        System.out.println(f);        //getClassLoader().getResource(fileName)        //用擷取到的類new一個新的對象        Object o=c.newInstance();        //接收該對象中所有的方法        Method[] method = c.getMethods();        System.out.println("此元素上的注釋:"+c.getDeclaredAnnotations());        for(Method m:method) {            if(m.getName().equals("m")) {            //方法選擇第一個參數傳遞對象,後面的參數傳遞方法參數            m.invoke(o);                        System.out.println("雜湊碼:"+m.hashCode());            }                        if(m.getName().equals("b")) {                m.invoke(o,1,2);                //得到參數類型                for(Class paramtype : m.getParameterTypes()) {                System.out.println("參數類型:"+paramtype.getName());                    }            }        }    }    }/*
//instanceof方法測試args返回的是否是一個class執行個體
 if(args[0] instanceof  String)
* @param args * */class T { public T(){ System.out.println("建構函式被調用了"); } public void m() { System.out.println("m函數被調用了"); } public void b(int i,int j) { System.out.println("b函數的結果:"+i+j); }}

 

 

一,利用反射自動為javabeen賦值

例 been:

package proxy;public class Notice{     String type;     String name;     String data;     String address;     String vill;     String upFile;     String num;     public String getName() {          return name;     }     public void setName(String name) {          this.name = name;     }     public String getData() {          return data;     }     public void setData(String data) {          this.data = data;     }     public String getAddress() {          return address;     }     public void setAddress(String address) {          this.address = address;     }     public String getVill() {          return vill;     }     public void setVill(String vill) {          this.vill = vill;     }     public String getUpFile() {          return upFile;     }     public void setUpFile(String upFile) {          this.upFile = upFile;     }     public String getNum() {          return num;     }     public void setNum(String num) {          this.num = num;     }     public String getType() {          return type;     }     public void setType(String type) {          this.type = type;     }}

插入資料類:

package cn.test;import java.lang.reflect.Field;import java.util.HashMap;public class ReflectDemo {    static HashMap<String,String> data;    static{         data=new HashMap<String,String>();           data.put("name","擬徵收土地公告");          data.put("type","測試公告");          data.put("data","2017-01-12");          data.put("address","成都市青羊區");          data.put("vill","二道街");          data.put("upFile","檔案具體的內容");          data.put("num","文號:國:001");          data.put("type","測試公告");    }    public static void main(String[] args)throws Exception {        Notice obj=new Notice();        test2(obj,data);        System.out.println(obj.getAddress());    }    public static void test2(Notice obj,HashMap<String,String> data) throws Exception {         Class cls=obj.getClass();         //getDeclaredFields():獲得某個類的所有聲明的欄位         Field[] fields = cls.getDeclaredFields();           for(Field field : fields){               String item=data.get(field.getName());                field.set(obj,item);           }    }}

 二,動態代理

通過類實現InvocationHandler介面重寫invoke方法實現

可在需要調用的方法前面首先調用其他方法,做到許可權控制

實作類別:

package proxy;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;public class myProxyDemo implements InvocationHandler{    Object aa;    public Object newProxy(Object aa) {        this.aa=aa;
//返回一個指定介面的代理類執行個體(擷取類載入地址,擷取類實現的介面)
return Proxy.newProxyInstance(aa.getClass().getClassLoader(),aa.getClass().getInterfaces(), this); } int count; public int count() { return count; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { befor(method,args);
//調用此執行個體 Object ad
= method.invoke(this.aa,args); return null; }
   //可通過重寫此方法完成不同功能
public void befor(Method method, Object[] args){ System.out.println("----------"); }}

測試類別:

public class TestProxy {  //UserManager一個普通的javabeen    public static void main(String[] args) {        myProxyDemo handler=new myProxyDemo ();        UserManager userManager=(UserManager) handler.newProxy(new UserManagerImpl());        userManager.addUser("ad", "da");    }}

 

Java:反射的常用用法,

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.