Java反射之配置文件

Java反射与配置文件有关的代码实例

配置文件是右键该工程,创建的File文件,文件名为properties,避免了硬编码。下面是文件的内容:

user=root
password=123456
className=com.hpe.reflect.Student
methodName=show

反射在配置文件方面的使用实例:

package com.hpe.reflect;

import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Properties;

import org.junit.Test;

public class TestOthers {

	// 获取运行时类的直接父类
	@Test
	public void test1() {
		Class<Person> clazz = Person.class;
		Class<? super Person> superclass = clazz.getSuperclass();
		System.out.println(superclass);
	}
	// 通过反射获取并运行配置文件
	@Test
	public void test2() throws Exception{
		// 获取配置文件的对象
		Properties p = new Properties();
		// 获取输入流,读取配置文件,将其以流的形式读取
		FileReader in = new FileReader(new File("properties"));
		// 将流加载到配置文件对象中
		p.load(in);
		// 释放资源
		in.close();
		// 获取用户名和密码
		String userName = p.getProperty("user");
		String password = p.getProperty("password");
		System.out.println("用户名" + userName + ";密码" + password);
		
		// 通过反射获取Class对象
		Class<?> clazz = Class.forName(p.getProperty("className"));
		// 获取show()方法
		Method method = clazz.getMethod(p.getProperty("methodName"));
		Student s = (Student)clazz.newInstance();
		//method.invoke(clazz.getConstructor().newInstance());
		method.invoke(s);
	}
	// 泛型擦除:程序编译后产生的字节码文件.class是没有泛型约束的,这种现象称为泛型的擦除
	@Test
	public void test3() throws Exception {
		ArrayList<Integer> arr = new ArrayList<>();
		arr.add(123);
		arr.add(456);
		// 获取ArrayList字节码对象
		Class<? extends ArrayList> c = arr.getClass();
		// 通过反射获得add
		Method method = c.getMethod("add", Object.class);
		// 调用方法
		method.invoke(arr, "abc");
		System.out.println(arr);
		
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值