用反射呼叫Method類的invoke方法

jeepc發表於2018-11-03
public class Person {

    private int age;

    public static void main(String[] args) {

        Class<?> clazz = Person.class;
        try {
            Object o = clazz.newInstance();
            Method setAge = clazz.getMethod("setAge",int.class);
            Method invoke = setAge.getClass().getMethod("invoke", Object.class, Object[].class);
            Object[] params = {12};
            invoke.invoke(setAge,o,params);
            System.out.println(o);//結果:Person{age=12}
            
          /*還可以這樣……
            Object o = clazz.newInstance();
            Method setAge = clazz.getMethod("setAge",int.class);
            Method invoke = setAge.getClass().getMethod("invoke", Object.class, Object[].class);
            Method invoke2 = setAge.getClass().getMethod("invoke", Object.class, Object[].class);
            Object[] params = {12};
            Object[] params2 = {o,params};
            invoke2.invoke(invoke,setAge,params2);
            System.out.println(o);
            */
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }


    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                '}';
    }
}
複製程式碼

相關文章