反射调用类中的方法

 使用反射调用类中的setter、getter方法

 1 package com.google.demo;
 2 import java.lang.reflect.Method;
 3 
 4 class Member{
 5     private String name;
 6     public void setName(String name) {
 7         this.name = name;
 8     }
 9     public String getName() {
10         return this.name;
11     }
12 }
13 public class JavaReflectDemo {
14     public static void main(String[] args) throws Exception {
15         Class<?> cls = Member.class;
16         String value = "小李老师";
17         Object object = cls.getDeclaredConstructor().newInstance();
18         String setMethodName = "setName";
19         Method setMethod = cls.getDeclaredMethod(setMethodName, String.class);
20         setMethod.invoke(object,value);
21         String getMethodName = "getName";
22         Method getMethod = cls.getDeclaredMethod(getMethodName);
23         System.out.println(getMethod.invoke(object));
24     }
25 }

运行结果:

小李老师

 

点赞