谢谢你的回复,下段代码是获取TestMethod类的方法数组,并调用,方法会访问到对应属性,会出错- package Test3;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- public class TestDemo {
- /**
- * @param args
- * @throws InstantiationException
- * @throws InvocationTargetException
- * @throws IllegalArgumentException
- * @throws IllegalAccessException
- */
- public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
- Class clazz = TestMethod.class;
- Method[] methods = clazz.getMethods();
- for (Method method : methods) {
- method.setAccessible(true);
- System.out.println(method.invoke(clazz.newInstance(),null));
- }
- }
- }
- class TestMethod{
- public String name = "zhangsan";
- public int x = 1;
- public String getName() {
- return name;
- }
- /*public void setName(String name) {
- this.name = name;
- }*/
- public int getX() {
- return x;
- }
- /*public void setX(int x) {
- this.x = x;
- }*/
-
- }
复制代码 |