Java反射特性--获取其他类实例并调用其方法

1. 代码结构

.
├── com
│   └── test
│      └── MyTest.java
└── MainCall.java

 

2. 代码内容

MyTest.java:

package com.test;

public class MyTest
{
    public void do_test() 
    {
        System.out.println("Doing test...\n");
    }
}

MaiCall.java

import java.lang.reflect.Method;

public class MainCall
{
    public static void main(String[] args)
    {
        System.out.println("Hello World!\n");

        Class<?> mt = null;
        try{
            mt = Class.forName("com.test.MyTest");
        }catch(Exception e) {
            e.printStackTrace();
        }

        System.out.println("ClassName: " + mt.getName());
        
        try{
            Method method = mt.getMethod("do_test");
            method.invoke(mt.newInstance());
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

3.编译

javac com/test/MyTest.java

javac MainCall.java

编译成功后:

.
├── com
│   └── test
│      ├── MyTest.class
│      └── MyTest.java
├── MainCall.class
└── MainCall.java

 

4. 执行

java MainCall得到输出:

Hello World!

ClassName: com.test.MyTest
Doing test...

posted @ 2016-09-28 21:16  泡面狂  阅读(852)  评论(0编辑  收藏  举报