Java中的反射(Reflection)

Main.java

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Properties;

public class Main {

	public static void main(String[] args) throws Exception {
		
		File configFile = new File("D:\\EclipseWorkspace\\TestReflection\\src\\config.ini");
		Properties properties = new Properties();
		properties.load(new FileInputStream(configFile));

		//simple reflection
		String className = (String)properties.get("className");
		String methodTellName = (String)properties.get("methodTell");

		Class<?> clz = Class.forName(className);
		Constructor<?> con = clz.getConstructor();
		Object obj = con.newInstance();

		Method methodTell = clz.getMethod(methodTellName);
		methodTell.invoke(obj);

		//reflection with packageName.className+constructor&method with parameter
		String classOliveName = (String)properties.get("classOliveName");
		String methodTellOliveName = (String)properties.get("methodTellOlive");
		
		Class<?> clzWithName = Class.forName(classOliveName);
		Constructor<?> conOlive = clzWithName.getDeclaredConstructor(String.class);
		Object objOlive = conOlive.newInstance("Cedar");
		
		Method methodTellOlive = clzWithName.getMethod(methodTellOliveName,String.class);
		methodTellOlive.invoke(objOlive,"Olive");
	}

}

Teacher.java


public class Teacher {

	public Teacher() {
	}

	public void tell() {
		System.out.println("this is teacher");
	}
	
	public void tellme(String catName) {
		System.out.println(catName + "is cute,said Teacher");
	}
}

Student.java


public class Student {

	//no need for constructor
//	public Student() {
//	}
	
	public void tell() {
		System.out.println("this is student");
	}
	
	public void tellme(String catName) {
		System.out.println(catName + "is cute,said Student");
	}
}

linan/Olive.java

public class Olive {

	public String he;
	public Olive(String he) {
		this.he = he;
		//System.out.println("this is Olive constructor");
	}

	public void tellOlive(String she) {
		System.out.println(he + " says " + she + " is cute");
	}
}

输出:

this is student
Cedar says Olive is cute

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值