java反射 关于方法

package com.tydic.test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestReflect
{
   public static <T> T execute(Class clazz,String method,Object args,Class<T> result) throws InstantiationException, IllegalAccessException
   {
       Object obj=clazz.newInstance();
       try {
           Method med=null;
           if(obj instanceof String)
           {
              med =clazz.getMethod(method);
              med.setAccessible(true);
           }                    
        return (T)  med.invoke(obj);                
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
       
       return  (T) new Boolean(true);
   }  
   public static void main(String[] args)
   {
       try {
        int bo=TestReflect.execute(String.class,"length","method",int.class);
        String str="hh";
        
        System.out.println(bo);
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
   }
}

 

     

 

posted @ 2013-08-02 16:13  100Mbps  阅读(224)  评论(0编辑  收藏  举报