1. 程式人生 > >Java:反射的常用用法,

Java:反射的常用用法,

註釋 load tint hash .get 控制 als demo ces

常用反射方法:

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:反射的常用用法,