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