import java.lang.reflect.*;
public class ReflectionExample {
private Class c;
private Object obj;
public ReflectionExample(String className, String propName, String propValue)
throws ClassNotFoundException, InstantiationException,
NoSuchMethodException, IllegalAccessException,
InvocationTargetException {
c = Class.forName(className);
obj = c.newInstance();
setProperty(propName, propValue);
String s = getProperty(propName);
}
private void setProperty(String name, String value)
throws ClassNotFoundException, NoSuchMethodException,
IllegalAccessException, InvocationTargetException {
String methodName = "set" + name.substring(0, 1).toUpperCase() +
name.substring(1);
Class[] paramTypes = {Class.forName("java.lang.String")};
String[] values = {value};
Method m = c.getMethod(methodName, paramTypes);
m.invoke(obj, values);
System.out.println("プロパティ " + name + " に " + value +
" をセットしました。");
}
private String getProperty(String name)
throws NoSuchMethodException,
IllegalAccessException, InvocationTargetException {
String methodName = "get" + name.substring(0, 1).toUpperCase() +
name.substring(1);
Class[] paramTypes = null;
Method m = c.getMethod(methodName, paramTypes);
String s = (String) m.invoke(obj, null);
System.out.println("プロパティ " + name + " の値は " + s + " です。");
return s;
}
public static void main(String[] args) throws Exception {
ReflectionExample my =
new ReflectionExample("my.sample.HelloWorld", "message", "Hello");
}
}
/* end.*/
|