假如有一个方法:public List a(Object obj){
      
}
a 方法要实现多态,也就是说可以接收任何类型的对象,我想在方法体里面知道对象的各种方法,使用反射能不能实现?

解决方案 »

  1.   


    public List a(Object obj){
         Class c = obj.getClass();
         Method[] method = c.getMethods(); 
    }   
      

  2.   


    package com.tutorinfo.forum;import java.lang.reflect.Method;
    import java.util.ArrayList;
    import java.util.List;public class GetMethod {

    /*
     * 返回参数中的对象的类的全部方法名
     */
    @SuppressWarnings("unchecked")
    public <T> List<String> a(T t){
    List<String> list=new ArrayList(); 

    if (null!=t){
    Class clazz=t.getClass();
    //对象反映此 Class 对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法
    //Method[] methods=clazz.getDeclaredMethods();  

    //返回一个包含某些 Method 对象的数组,这些对象反映此 Class 对象所表示的类或接口(包括那些由该类或接口声明的以及从超类和超接口继承的那些的类或接口)的公共 member 方法。
    Method[] methods=clazz.getMethods(); 
                for(Method m:methods){
                 list.add(m.toString());
                }
    }
    return list;
    }

    public static void main(String[] args){
    GetMethod gm=new GetMethod();
    List<String> methods=gm.a(gm);  //测试一个对象,获取它全部的方法名
    System.out.println(methods);
    }}
      

  3.   


    你看看反射中 method类的invoke方法
      

  4.   

    method[index].invoke 方法需要的参数穿进去就可以