Java反射实例

原文参考:
http://blog.csdn.net/sinat_38259539/article/details/71799078

①有两个提供服务的类ReflectService1,ReflectService2如下:

public class ReflectService1
{

public ReflectService1(){};
public void doService1(){
    System.out.println("Do Service1.");
}

}

public class ReflectService2
{

public ReflectService2(){};
public void doService2(){
    System.out.println("Do Service2.");
}

}

②有1个配置文件,指定Main方法中调用哪个服务的哪个方法:

class=ReflectService2
method=doService2

③主类ReflectMain中读取配置文件的配置,然后进行方法调用:

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Properties;
public class ReflectMain
{

public static void main(String args[]){
    File springConfFile = new File("F:\\Learn\\Java\\workspace\\spring\\ReflectTest\\src\\spring.properties");
    Properties springConf = new Properties();
    try
    {
        springConf.load(new FileInputStream(springConfFile));
        //获取配置文件中配置的类
        String className = (String)springConf.get("class");
        System.out.println("className: " + className);
        //获取配置文件中配置的方法
        String method = (String)springConf.get("method");
        System.out.println("method: " + method);
        //获取到对应的类对象
        Class clazz = Class.forName(className);
        //Class cla = ReflectMain.class;
        System.out.println("clazz name: " + clazz.getName());
        //获取到该类对象下的对应方法
        Method m = clazz.getMethod(method, null);
        System.out.println("method name: " + m.getName());
        //通过类对象获取构造器
        Constructor c = clazz.getConstructor(null);
        System.out.println("constructor name: " + c.getName());
        //通过构造器构造新的对象实例
        Object o = c.newInstance(null);
        System.out.println("object name: " + o.toString());
        //调用对象实例的方法
        m.invoke(o,null);
    }catch(Exception e){
        e.printStackTrace();
    }
}

}

上一篇:Java中数组,List,Set的相互转换注意点(样例)


下一篇:经典算法面试题目-判断两个字符串是否是变位词(1.4)