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