码迷,mamicode.com
首页 > 其他好文 > 详细

反射例子(配置文件)

时间:2018-09-22 19:54:15      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:close   const   一个   cto   hid   cli   bsp   get   return   

配置文件

className = fanshe.Student1
showInfo = show1

类student1

public class Student1 {
	public Student1() {
		System.out.println("调用了Student1 无参构造函数");
	}
	public void show1(){
		System.out.println("调用了show1()方法");
	}
}

测试类

public class Test {

	public static void main(String[] args) throws Exception{		
			//1. 获取类
			Class clazz = Class.forName(getValue("className"));
			//2. 获取showinfo方法
			Method m_showInfo = clazz.getMethod(getValue("showInfo"));
			//3.调用showInfo()方法
			   //3.1 实例化一个类对象,invoke中必须传入类对象的实例
				Object obj = clazz.getConstructor().newInstance();
			   //3.2  用实例化好的类对象去调用方法
			     m_showInfo.invoke(obj);
	}	
    
    
	public static String getValue(String key) throws Exception{
		Properties pro = new Properties();//获取配置文件对象	
		FileReader file = new FileReader("proInfo.txt");//获取输入流对象
		pro.load(file);//加载
		file.close();//关闭流对象
		return pro.getProperty(key);//返回需要取的目标值
		
	}
}

  

 

输出

调用了Student1 无参构造函数
调用了show1()方法

  



反射例子(配置文件)

标签:close   const   一个   cto   hid   cli   bsp   get   return   

原文地址:https://www.cnblogs.com/zzh-blog/p/9690756.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!