Java反射机制的作用,还有就是动态语言就是程序运行时,允许改变程序结构或变量类型。我不是很理解 什么叫做在运行时允许改变?????

解决方案 »

  1.   

    你可以写在文件中:Class.forName("从文件中读取").newInstance;
      

  2.   

    平时写程序,创建对象的时候就用new,你程序new多少个就创建多少个对象。
    但是现在要创建不定数量或不定类型的对象,只能用反射机制了。。
      

  3.   

    public class Test {
    private Test() {
    } public int add(int param1, int param2) {
    return param1 + param2;
    } public String echo(String msg) {
    return "echo:" + msg;
    } public static void main(String[] args) throws Exception {
    Class classType = Test.class;
    Object invokeTester = classType.newInstance();
    // 调用InvokeTester对象的add()方法
    Method addMethod = classType.getMethod("add", new Class[] { int.class,
    int.class });
    Object result = addMethod.invoke(invokeTester, new Object[] {
    new Integer(100), new Integer(200) });
    System.out.println((Integer) result);
    // 调用InvokeTester对象的echo()方法
    Method echoMethod = classType.getMethod("echo",
    new Class[] { String.class });
    result = echoMethod.invoke(invokeTester, new Object[] { "Hello" });
    System.out.println((String) result);
    }
    }
    这个Test不能被new ,但是通过反射,调用了他的方法