Java反射机制

Java反射机制

 一:什么事反射机制

 简单地说,就是程序运行时能够通过反射的到类的所有信息,只需要获得类名,方法名,属性名。

 二:为什么要用反射:    

静态编译:在编译时确定类型,绑定对象,即通过。    

动态编译:运行时确定类型,绑定对象。动态编译最大限度发挥了java的灵活性,体现了多态的应用,有以降低类之间的藕合性。    

比如,一个大型的软件,不可能一次就把把它设计的很完美,当这个程序编 译后,发布了,当发现需要更新某些功能时,我们不可能要用户把以前的卸载,再重新安装新的版本,这样的话,这个软件肯定是没有多少人用的。采用静态的话,需要把整个程序重新编译一次才可以实现功能 的更新,而采用反射机制的话,它就可以不用卸载,只需要在运行时才动态的创建和编译,就可以实现该功能。     

三:如何使用反射

 首先得根据传入的类的全名来创建Class对象。
    Class c=Class.forName("className");注明:className必须为全名,也就是得包含包名,比如,cn.netjava.pojo.UserInfo;
    Object obj=c.newInstance();//创建对象的实例
    OK,有了对象就什么都好办了,想要什么信息就有什么信息了。  
    获得构造函数的方法
    Constructor getConstructor(Class[] params)//根据指定参数获得public构造器

    Constructor[] getConstructors()//获得public的所有构造器

    Constructor getDeclaredConstructor(Class[] params)//根据指定参数获得public和非public的构造器

    Constructor[] getDeclaredConstructors()//获得public的所有构造器
    获得类方法的方法
    Method getMethod(String name, Class[] params),根据方法名,参数类型获得方法

    Method[] getMethods()//获得所有的public方法

    Method getDeclaredMethod(String name, Class[] params)//根据方法名和参数类型,获得public和非public的方法

    Method[] getDeclaredMethods()//获得所以的public和非public方法   

     最后调用方法

      invoke(对象,参数);

四:举一个简单的例子

public class Text {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException  {
        //输入        
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入你的类:");
        String str=sc.next();
        while(true){        
                //装载一个类
                Class c=Class.forName(str);
                //获得构造器
                Constructor ct =c.getConstructor();//String是构造函数需要的参数类型
                //根据构造器获得对象                        
                Object o=ct.newInstance();//参数是构造方法中要传入的参数    
                System.out.println("请输入方法名:");
                
                String oName=sc.next();//输入对象的名称
                
                System.out.println("请输入参数:");
                
                int canshu =sc.nextInt();//方法的参数            
                //获得方法
                Method me=c.getMethod(oName,int.class);    
                //在对象上调用方法,第一个参数是对象。第二个参数是对象方法的参数
               String a=  me.invoke(o,canshu).toString();
                System.out.println("最后的结果是:"+a);            
        }    
    }    
}
原文地址:https://www.cnblogs.com/java-7/p/6015254.html