JAVA反射
程序员文章站
2024-01-21 14:40:22
...
public class T {
/**
* @param args
*/
public static void main(String[] args) {
String s = "com.反射.Customer";
T t = new T();
t.getFields(s);
t.getMethods(s);
t.excMethods(s);
}
public void getFields(String className) {
try {
Class c = Class.forName(className);
System.out.println("属性:");
Field f[] = c.getDeclaredFields();
for (int i = 0; i < f.length; i++) {
System.out.println(f[i].getName());
}
} catch (Throwable e) {
System.err.println(e);
}
}
public void getMethods(String className) {
try {
Class c = Class.forName(className);
System.out.println("方法:");
Method m[] = c.getDeclaredMethods();
for (int i = 0; i < m.length; i++) {
System.out.println(m[i].toString());
}
} catch (Throwable e) {
System.err.println(e);
}
}
public void excMethods(String className) {
try {
Class c = Class.forName(className);
Object o = c.getConstructor(new Class[] {}).newInstance(
new Object[] {});
Method sAge = c.getMethod("setAge", new Class[] { int.class });
Method gAge = c.getMethod("getAge", null);
Method sName = c.getMethod("setName", new Class[] { String.class });
Object[] args1 = { new Integer(25) };
sAge.invoke(o, args1);
Integer AGE = (Integer) gAge.invoke(o, null);
System.out.println("the Customer age is: " + AGE);
Object[] args2 = { new String("李四") };
sName.invoke(o, args2);
} catch (Throwable e) {
System.err.println(e);
}
}
}
上一篇: 1设计模式-工厂模式
下一篇: Java反射学习