- class User{
- private String name;
- private int age;
- @Override
- public String toString(){
- return "User{" + "name=" +name + ", age="+age+"}";
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- }
现在定义了一个类 User, 这个类有各种的方法和参数. 我们将这个类实例化之后, 再动态调用它的方法来给它赋值.
- public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
- User user = new User();
- Class clz = user.getClass();
- Method method = clz.getMethod("setName", String.class);
- Method method1 = clz.getMethod("setAge", int.class);
- method1.invoke(user,21);
- method.invoke(user,"fortheone");
- System.out.println(user);
- }
来源: https://www.cnblogs.com/hetianlab/p/13402503.html