其他分享
首页 > 其他分享> > 反射的简单用法

反射的简单用法

作者:互联网

 1 package com.sunny.core.sunnycore.ssm;
 2 
 3 import lombok.AllArgsConstructor;
 4 import lombok.Data;
 5 import lombok.NoArgsConstructor;
 6 
 7 /**
 8  * @Description: TODO
 9  * @Author Lg
10  * @Date 2022/3/30
11  */
12 @Data
13 @NoArgsConstructor
14 @AllArgsConstructor
15 public class User {
16     private String name;
17     private int age;
18     private String sex;
19 }
View Code
 1 package com.sunny.core.sunnycore.ssm;
 2 
 3 import java.lang.reflect.Constructor;
 4 import java.lang.reflect.InvocationTargetException;
 5 import java.lang.reflect.Method;
 6 
 7 /**
 8  * @Description: TODO
 9  * @Author Lg
10  * @Date 2022/3/30
11  */
12 public class ReflectionTest {
13     public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
14         //获取class对象
15         Class aClass = Class.forName("com.sunny.core.sunnycore.ssm.User");
16 
17         //获取User对象
18         User user1 = (User) aClass.newInstance();
19         System.out.println(user1);
20 
21         //通过构造器获取对象
22         Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class, int.class, String.class);
23         User user2 = (User) declaredConstructor.newInstance("Lg", 25, "男");
24         System.out.println(user2);
25 
26         //通过反射调用方法
27         Method setName = aClass.getDeclaredMethod("setName", String.class);
28         setName.invoke(user1,"张三");
29         System.out.println(user1);
30         setName.invoke(user2,"李四");
31         System.out.println(user2);
32 
33     }
34 }
View Code

 

 结果:

 

 

标签:反射,String,aClass,用法,User,简单,println,import,class
来源: https://www.cnblogs.com/LgZml/p/16079606.html