class反射

                                                                                                         关于class反射总结

 

             1,对象转class对象三种方法。以及区别

                 1)对象.class   --告诉我们实际所有的类都可以获取类类型.任何一个类都有一个静态的class方法

                 2)getClass(String name) --参数name为Class对应的类的全名(包括包名); 如果传递的是哪个子类的对象。这个就是哪个子类的具体类型

                            例子  Person person = new Person();

                                    Class clazz = person.getClass();

                3)  调用Class类的forName(String name)静态方法,参数name为Class对应的类的全名(包括包名);还代表了动态加载类 (编译时刻是静态加载类。运行时是动态加载类)

                       例子:String className = "com.sh.pojo.Person";

                                  Class clazz = Class.forName(className);

              应用实例:

                             旧代码 ():

                                               

 

 

               出现的问题

                                 1 项目中如果没有Excel类或者Word类就会编译报错 . 因为new 创建对象是静态加载,在编译时刻就会加载。

                                 2 每次新增一个办公工具都要修改这块代码。耦合度高.

               解决方法有很多。这个是之一

                             他们两个类都实现一个公共接口 例如OfficeAble 。使用forName() 动态加载。以后只需要实现公共类就好。

                               

 

 

                             --------------------------------------------------------------------------------分割线-------------------------------------------------------------------------------

 

 

                  2, 反射常用api

                                 

 public static void main(String[] args) throws Exception {
        //获取字节码文件
        Class<?> rName = Class.forName(全限定类名);
        
        /**
         * 获取构造方法
         * 
         */
        //获取___所有public的构造方法,
        //如果还要获取所有的构造方法用getDeclaredConstructors()方法
        Constructor<?>[] constructors = rName.getConstructors();
        //获取___指定的构造方法,这获取的是无参构造方法,
        //要获取有参的请在行参列表上写上(数据类型.class,数据类型.class);
        Constructor<?> constructor = rName.getConstructor();
        //调用___无参构造方法
        Object newInstance = constructor.newInstance();
        
        /**
         * 获取方法
         * 
         */
        //获取___类中所有的public修饰的方法,其中包括父类的方法。
        //getDeclaredMethods()方法 获取的是所有的该类自己声明的方法。不问访问权限
        Method[] methods = rName.getMethods();
        //获取___指定的方法,这获取的是无参方法,
        //要获取有参的请在行参列表上写上(指定的方法名,数据类型1.class,数据类型2.class);
        Method method = rName.getMethod(方法名);
        //调用___非static修饰的方法需要invoke(对象,实参1,实参2),
        //有static修饰的方法需要invoke(null,实参1,实参2)。
        //我这调用的非static修饰方法没有参数就只需一个对象
        method.invoke(newInstance);
        /**
         * 获取字段
         * 
         */
        //获取___类中的public字段。如果还要获取所有的字段用getDeclaredFields()方法自己声明的,不问访问权限 
        Field[] fields = rName.getFields();
        //获取___指定的字段。
        Field field = rName.getDeclaredField(指定的字段名);
        //设置___指定的字段,非static修饰,set(对象,值);有static修饰,set(null,值)
        field.set(newInstance,5.2);
        //调用___指定字段的值,非static修饰,get(对象);有static修饰,get(null)
        Object object = field.get(newInstance);
        System.out.println("指定字段的值=="+object);
        
        /**
         * 破坏包装declaredField.setAccessible(boolean)破坏封装,可以调用私有成员
         * true:破环
         * false:默认值,不破坏
         */
        Field field2 = rName.getDeclaredField(私有化的字段名);
        //破坏封装,不让字段私有化
        field2.setAccessible(true);
        //设置字段的值
        field2.set(newInstance,值);
        //调用设置后的字段值,并打印
        Object object2 = field2.get(newInstance);
        System.out.println("破坏封装==="+object2);
        
        //获取全限定类名
        String name = rName.getName();
        System.out.println("全限定类名: "+name);
        
        //获取类名简写
        String simpleName = rName.getSimpleName();
        System.out.println("类名简写: "+simpleName);
    }
}

 

       2) 反射获取注解

                2.1)     Method[] methods = cl1.getDeclaredMethods();

                            for (Method method : methods) {

                                GetMapping getRequestMothed = (GetMapping) method.getAnnotation(GetMapping.class);

                               PutMapping putRequestMothed = (PutMapping) method.getAnnotation(PutMapping.class);

                                PostMapping postRequestMothed = (PostMapping) method.getAnnotation(PostMapping.class);

                               DeleteMapping deleteRequestMothed = (DeleteMapping)method.getAnnotation(DeleteMapping.class);

                       //获取类注解的value值

                      String[] value1 = getRequestMothed .value();

                      String[] value2 = putRequestMothed .value();

                     String[] value3 = postRequestMothed .value();

                    String[] value4 = deleteRequestMothed.value(); }

 

 

               2.2) 获取自定义注解

                           //获取类名的包名地址

                         printClass = Class.forName("com.lxp.demo.Schedules.TestThtread");

                         //java反射机制获取所有方法名

                        Method[] declaredMethods = printClass.getDeclaredMethods();

for (Method declaredMethod : declaredMethods) {
String isNotNullStr = "";

// 判断是否方法上存在注解 MethodInterface

boolean annotationPresent = declaredMethod.isAnnotationPresent(MethodInterface.class);

if (annotationPresent) {
// 获取自定义注解对象

MethodInterface methodAnno = declaredMethod.getAnnotation(MethodInterface.class);

// 根据对象获取注解值

isNotNullStr = methodAnno.name();

}

list.add(new KeyValueDto(declaredMethod.getName(),isNotNullStr));

}

//排序(按照方法名称排序)

Collections.sort(list);

System.out.println(list.toString());

} catch (Exception e) {
e.printStackTrace();

}

}

实体类 KeyValueDto

public class KeyValueDto implements Comparable{
private String key;

private String value;

public KeyValueDto(String key, String value) {
this.key = key;

this.value = value;

}

public String getKey() {
return key;

}

public void setKey(String key) {
this.key = key;

}

public String getValue() {
return value;

}

public void setValue(String value) {
this.value = value;

}

@Override

public int compareTo(KeyValueDto o) {
return o.getKey().compareTo(this.key);

}

@Override

public String toString() {
return "{" +

"key='" + key + '\'' +

", value='" + value + '\'' +

'}';

}

}

4.最后一步就是测试和结果了

public static void main(String[] args) {
testJava();
————————————————
版权声明:本文为CSDN博主「苏额」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_33356324/article/details/114039097

 

 

            

posted @ 2021-09-29 15:49  MENG_NULL  阅读(331)  评论(0)    收藏  举报