编写程序,熟悉反射机制

import java.lang.reflect.*;

public class TestReflection{

    public static void main(String[] args) throws Exception{
        String str = "T";
        Class c = Class.forName(str);
        T t =(T)c.newInstance();
        for(Method m : c.getMethods()){
            if(m.getName().equals("m1")){
                m.invoke(t,234);
                System.out.println(m.getReturnType().getName());
                for(Class temp : m.getParameterTypes()){
                    System.out.println(temp.getName());
                }
            }
            
            if(m.getName().equals("m2")){
                m.invoke(t,2,5.0);
                System.out.println(m.getReturnType().getName());
                m.getParameterTypes();
                for(Class temp : m.getParameterTypes()){
                    System.out.println(temp.getName());
                }
            }
        }
    }

}

class T{
    
    static{
        System.out.println("static");
    }
    
    int i;
    double j;
    
    public int m1(int i){
        this.i = i;
        System.out.println("i = " + i);
        return i;
    }
    
    public double m2(int i , double j){
        this.i = i;
        this.j = j;
        System.out.println("i + j = " + (i + j));
        return i + j;
    }
    
}

 

posted @ 2020-03-16 15:59  yxfyg  阅读(168)  评论(0)    收藏  举报