一直困扰我的java反射

由于是菜鸟 呵呵 一直对java的框架struts struts2 spring hibernate 等 从配置文件中取得类信息  就可以创建和操纵类对象 不明所以

一直耿耿于怀 今日 忍无可忍 决定探索

 

首先: 通过一个类的父接口的Class对象获得方法对象 method , method.invoke(子类对象,args); 能否调用子类对象的方法 答案是:能

  如 import java.lang.reflect.*;

public class Reflect1 {

  public static void main(String[] args) {
   
   try {
    Class clazz = Animal.class;
    Method method = clazz.getMethod("cry",new Class[]{});//此处也可以 clazz.getMethod("cry");
    Cat cat = new Cat();
    method.invoke(cat,new Object[]{});//此处也可以.invoke(cat);
   }catch(Exception ex) {ex.printStackTrace();}
  }
 
}

interface Animal {

 void cry() ;

 
}

class Cat implements Animal{

  public void cry() {
   System.out.println("miao");
  }
 
}

这样的话 框架就明晰了

 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 

下面我特地的实现了一个不事先知道目标类的代理类 感觉以前的一位好朋友说的一句话特别有道理 当时没有理解 现在有些理解了

 “你的对象都被人拿走了 不还人为刀俎 我为鱼肉 了” 一句话 是反射的全部 呵呵

import java.lang.reflect.*;
public class ReflectTest {

  public static void main(String[] args) {
    try {
       
     
       Person person2 = new Person();
       InvocationHandler handler = new Handler(person2) {
      
         public Object invoke(Object proxy,Method method,Object[] args){
             
            Object obj = null;
            System.out.println("start");
            try {
             System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
             obj = method.invoke(proxy,args);
             }catch(Exception ex){System.out.println("error");}
            System.out.println("end");
            return obj;
          }     
     
        };
 
      Animal proxy = new PersonProxy(handler);
      proxy.setId(5);
      System.out.println(proxy.getId());
      
      }catch(Exception ex) {
       ex.printStackTrace();
       }

  }
}

interface Animal {
 void setId(int id);
 int getId();
}
class Person implements Animal{
  private int id;
  public void setId(int id) {
   this.id = id;
  }
  public int getId() {
   return this.id;
  }
}

abstract class Handler implements InvocationHandler {
 
  public Person person;
 
 
   Handler(Person p) {

   this.person = p;
  }
 
  public abstract Object invoke(Object proxy,Method method,Object[] args);
}

final class PersonProxy extends Proxy implements Animal {
 
  private InvocationHandler handler;
 
  Method invokemethod = null;
 
  Object target = null;
 
  public PersonProxy(InvocationHandler invokehandler) {
     
     super(invokehandler);
     this.handler = invokehandler;
  try{
      invokemethod = this.handler.getClass().getMethod("invoke",new Class[]              

{Object.class,Method.class,Object[].class});
     
     }catch(Exception ex){}

    System.out.println(this.handler.getClass());
 
    Field[] fields = this.handler.getClass().getFields();
    
    System.out.println("----------------------------------------");
    System.out.println(fields.length);
    for(Field f : fields) {
     
      System.out.println(f.getName());
      System.out.println(f.getDeclaringClass());
      System.out.println(f.getType());
     if(f.getType().getInterfaces()[0] == this.getClass().getInterfaces()[0]){
          try{
           
           target = f.get(this.handler);
           System.out.println("target:"+target);
           }catch(Exception ex){}
           break;
      }else {continue;}
    }
  }
  public void setId(int id) {
   Method method = null;
    try {
     method = this.getClass().getInterfaces()[0].getMethod("setId",int.class);
     }catch(Exception ex) {}
    try {
    // handler.invoke(this,method,id);
   invokemethod.invoke(handler,new Object[]{target,method,new Object[]{new Integer(id)}});
      }catch(Exception ex){}
   
  }
 
   public int getId() {
    Method method = null;
    System.out.println("getId1");
     try{
      method = this.getClass().getInterfaces()[0].getMethod("getId",new Class[]{});
      System.out.println("getId:"+method);
       }catch(Exception ex){}
     Object obj = null;
      try{
       // obj = handler.invoke(this,method,new Object[]{});
        System.out.println("target:"+target);
        obj = invokemethod.invoke(handler,new Object[]{target,method,new Object[]{}});  
         }catch(Exception ex){}
     
       return ((Integer)obj);
  }
}

posted on 2012-03-16 11:11  wensky  阅读(177)  评论(0编辑  收藏  举报

导航