📄 reflecttest.java
字号:
package cn.itcast.jdbc;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectTest {
/**
* @param args
* @throws Exception
* @throws NoSuchMethodException
*/
public static void main(String[] args) throws NoSuchMethodException,
Exception {
TestBean oa = new TestBean("test");
refl(oa, "showMessage");
}
static void refl(Object obj, String methodName)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException, InstantiationException, Exception,
NoSuchMethodException {
Class clazz = obj.getClass();
Method[] ms = clazz.getDeclaredMethods();
for (int i = 0; i < ms.length; i++) {
System.out.println(ms[i].getName());
if (ms[i].getName().equals(methodName)) {
ms[i].invoke(obj, null);
}
}
Constructor con = clazz.getConstructor(new Class[] { String.class,
int.class });
Object instance = con.newInstance(new Object[] { "Hello, World", 30 });
System.out.println(instance);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -