注解和反射
一. 反射
public class Demo01 {
public static void main(String[] args) {
//类---〉对象
Person person=new Person("Wan",11);
Class<?> clazz=person.getClass();
System.out.println(clazz.getName()); //com.demo.Person
try {
Class<?> clazz1=Class.forName("com.demo.Person");
Person person2=(Person) clazz1.newInstance();
System.out.println(person2);
//反射 可以获取类中所有方法属性
Constructor [] constructors=clazz1.getDeclaredConstructors();
for (Constructor constructor : constructors) {
System.out.println(constructor);
}
System.out.println("==获取属性==");
Field[] fields=clazz1.getDeclaredFields();
for (Field field : fields) {
System.out.println(field);
if(field.getName().equals("age")){
field.setAccessible(true);
field.set(person2, 7);
}
}
System.out.println("person2 age"+person2.getAge());
System.out.println("==获取方法==");
Method[] methods =clazz1.getDeclaredMethods();
for (Method method : methods) {
System.out.println(method.getName());
if(method.getName().equals("play")){
method.setAccessible(true);
method.invoke(person2, "123");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
1.1 概念
正常情况下如果已经有一个类,则肯定可以通过类创建对象;那么如果现在要求通过一个对象找到一个类的名称,此时就需要用到反射机制
实例化对象-----〉getClass()方法------〉得到完整的“包.类”名称
取得类的结构
Constructor
表示类中的构造方法
Field
表示类中的属性
Method
表示类中的方法
二.注解
public class Demo01 {
//注解 reflect 无注解 不反射
//@Override
public static void main(String[] args) {
Student student = new Student();
Class<?> clazz = student.getClass();
Method[] methods = clazz.getDeclaredMethods();
for(Method method:methods){
//判断method 是否带有注解
boolean b = method.isAnnotationPresent(MyAnnotation.class);
MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
if(b){
//如果有注解 通过注解方式赋zhi
System.out.println(method.getName());
if(method.getName().equals("setName")){
try {
method.invoke(student,myAnnotation.name());
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(method.getName().equals("setAge")){
try {
method.invoke(student,myAnnotation.age());
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
System.out.println(student.getAge());
System.out.println(student.getName());
}
}
2.1 Annotation
可以用来修示类,属性,方法Annotation不影响程序运行,无论是否使用Annotation代码都可以正常执行
2.2 系统内建的Annotation
@Override
覆写的Annotation
@Deprecated
不赞成使用的Annotation
@SuppressWarnings
压制安全警告的Annotation
2.3 自定义的Annotation
[public] @interface Annotation 名称{ 数据类型 变量名称();}