Java反射有多强?它拥有这五大神奇功能( 二 )

public interface LoginMapper {boolean login(String code,String password);}import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Controller;import zwz.pojo.User;import java.lang.annotation.Annotation;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.lang.reflect.Parameter;public class ReflexTest {public static void main(String[] args) throws Exception {User user = new User();// 方式一 类获取Class userClass = User.class;// 方式二 对象获取Class userClass2 = user.getClass();// 类完整路径String className = userClass.getName();// 包路径String packagePath = userClass.getPackage().getName();// 类名String simpleClassName = userClass.getSimpleName();// 获取父类String fatherClassName = userClass.getSuperclass().getSimpleName();// 获取接口Class[] interfaces = userClass.getInterfaces();// 根据class创建对象User user1 = (User) userClass.getDeclaredConstructor().newInstance();// 获取单个属性Field oneField = userClass.getDeclaredField("code");// 获取单个公有属性Field onePublicField = userClass.getField("grade");// 获取全部属性Field[] fields = userClass.getDeclaredFields();// 获取全部公有属性Field[] publicFields = userClass.getFields();for (Field field : fields) {//让我们在用反射时访问私有变量field.setAccessible(true);// 属性名field.getName();// 变量类型field.getType().getName();// 获取对象中该属性的值field.get(user1);// set 对象中该属性的值field.set(user1,"admin");}// 获取类中单个公有方法Method publicMethod = userClass.getMethod("login", String.class, String.class);// 获取类中单个方法Method method =userClass.getDeclaredMethod("login", String.class, String.class);// 获取类所有公有方法Method[] methods = userClass.getMethods();// 获取类所有方法Method[] publicMethods = userClass.getDeclaredMethods();// 运行方法method.invoke(new User(),"admin","123456");// 获取公有构造器Constructor[] publicConstructors = userClass.getDeclaredConstructors();// 获取所有构造器Constructor[] constructors = userClass.getConstructors();for (Constructor constructor : constructors) {// 构造器名称 等同类名String name = constructor.getName();// 构造器参数Parameter[] parameters = constructor.getParameters();}User user2 = (User) constructors[1].newInstance("admin", "123456", "95.8");// 获取类的注解Annotation[] annotations = userClass.getDeclaredAnnotations();// 获取字段的所有注解Annotation[] anns = userClass.getDeclaredField("code").getAnnotations();// 获取字段的单个注解Value annValue = http://kandian.youth.cn/index/userClass.getDeclaredField("code").getAnnotation(Value.class);// 注解不存在返回 nullController annController = userClass.getDeclaredField("code").getAnnotation(Controller.class);System.out.println("END!");}}作者:郑为中
原文链接: