package cn.itcast.domain;
public class Person {
private String name;
private int age;
public String a;
protected String b;
String c;
private String d;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public void eat(){
System.out.println("eat...");
}
public void eat(String food){
System.out.println("eat..."+food);
}
}
配置文件:
className=cn.itcast.domain.Person
methodName=eat
package cn.itcast.reflect;
import cn.itcast.domain.Person;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
/**
* 假设框架类
* 案例:写一个“框架类”,不能改变该类的任何代码的前提下,可以创建任意类的对象,可以执行任意方法
* 实现:
* 1.配置文件
* 2.反射
* 步骤:
* 1.将需要创建的对象的全类名和需要执行的方法定义在配置文件中
* 2.在程序中加载读取配置文件
* 3.使用反射技术来加载类文件进内存
* 4.创建方法
* 5.执行方法
*/
public class ReflectTest {
public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
//可以创建任意类的对象,可以执行任意方法
/*
前提:不能改变该类的任何代码,可以创建任意类的对象,可以执行任意方法
*/
/*Person p = new Person();
p.eat();*/
//1.加载配置文件
//1.1创建Properties对象
Properties pro = new Properties();
//1.2加载配置文件,转换为一个集合
//1.2.1获取class目录下的配置文件
ClassLoader classLoader = ReflectTest.class.getClassLoader();
InputStream is = classLoader.getResourceAsStream("pro.properties");
pro.load(is);
//2.获取配置文件中定义的数据
String className = pro.getProperty("className");
String methodName = pro.getProperty("methodName");
//3.加载该类到内存
Class cls = Class.forName(className);
//4.创建对象
Object obj = cls.newInstance();
//5.获取方法对象
Method method = cls.getMethod(methodName);
//6.执行方法
method.invoke(obj);
}
}