zoukankan      html  css  js  c++  java
  • 4、反射-类的构造器:Constrctor

    类的构造器:Constrctor

            Class clazz = Class.forName("cn.com.mrchengs.constrctor.Student");
    
            //1、获取全部的构造器
            Constructor[] constructors = clazz.getConstructors();
            for (Constructor constructor : constructors){
                System.out.println(constructor);
            }
    
            //2、获取某一个构造器
            Constructor<Student> constructor = clazz.getConstructor(String.class, int.class);
            System.out.println(constructor);
    
            //3、调用newInstance()方法创建对象
            Student student = constructor.newInstance("MrChengs", 22);
            System.out.println(student);

    小实例

    //要求Student中的age的范围再0-100
        //通过反射的方式感知到方法
        @Test
        public void  test() throws ClassNotFoundException, NoSuchMethodException, 
            IllegalAccessException, InvocationTargetException, InstantiationException { Class clazz
    = Class.forName("cn.com.mrchengs.constrctor.Student"); Object obj = clazz.newInstance(); Method method = clazz.getDeclaredMethod("setAge", int.class); method.setAccessible(true); int val = 20; Annotation an = method.getAnnotation(AgeValidator.class); if(an != null){ if(val < 0 || val > 100){ throw new RuntimeException("非法的年龄"); } } method.invoke(obj, 10); System.out.println(obj); }

     自定义注解

    @Retention(RetentionPolicy.RUNTIME)//运行时可见
    @Target(value={ElementType.METHOD})
    public @interface AgeValidator {
    
    }

     Student

        @AgeValidator
        public void setAge(int age) {
            this.age = age;
        }

  • 相关阅读:
    [循环卷积]总结
    [FFT/NTT/MTT]总结
    [BZOJ 4870] 组合数问题
    [BZOJ 4809] 相逢是问候
    [BZOJ 4591] 超能粒子炮-改
    __getattribute__
    __repr__
    __reduce__
    数据库查询转excel小工具
    Git常用操作
  • 原文地址:https://www.cnblogs.com/Mrchengs/p/10933949.html
Copyright © 2011-2022 走看看