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;
    }

 

转载于:https://www.cnblogs.com/Mrchengs/p/10933949.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值