您现在的位置是:首页 > 文章详情

Java反射实例

日期:2018-03-11点击:440

原文参考:
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();
    }
}

}

原文链接:https://yq.aliyun.com/articles/531021
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章