Java反射简例

来源:互联网 发布:adobe creative软件 编辑:程序博客网 时间:2024/06/16 19:44

简单的使用反射做了一个例子,然后逐步深化吧!
首先建立一个类,用于调用:

public class TestFile {        public static void main(String[] args) {            TestFile testFile = new TestFile();            testFile.sayHello("abc");        }        public void sayHello(String hello){            System.out.println(hello);        }        public void introduce(){            System.out.println("I am eclipse");        }        public void getInfo(String name, int age){            System.out.println("name="+name+"age="+age);        }

反射调用方法是可能有多个参数,这时是需要指定各个参数的类型的,而且不会自动拆箱装箱,比如方法的参数定义为int类型,在使用反射调用时,指定Integer类型,这时就会抛错,然后就是具体的反射调用文件:

        try {            //这里如果没有参数则不需要加任何内容,只需要指定方法名称,如果有参数则需要指定每个参数的类型            //**注意,包装类和非包装类并不是兼容的。            Method declaredSayHelloMethod = TestFile.class.getDeclaredMethod("sayHello",String.class);            Method declaredIntroduceMethod = TestFile.class.getDeclaredMethod("introduce");            Method declaredInfoMethod = TestFile.class.getDeclaredMethod("getInfo",String.class,int.class);            TestFile testFile = new TestFile();            declaredSayHelloMethod.invoke(testFile,"abcd");            declaredIntroduceMethod.invoke(testFile);            declaredInfoMethod.invoke(testFile, "abc",132);            } catch (Exception e) {            // TODO Auto-generated catch block                e.printStackTrace();            }
原创粉丝点击