注解
元注解
@Target:用于描述注解的使用范围
@Rention:表示需要在什么什么级别保存该注释信息,用于描述注解的生命周期。(source<class<runtime)
@Document:说明该注解将被包含在javadoc中。
@Inherited:说明子类可以继承父类中的该注解。
反射
一个类在内存中只能有一个Class对象
一个类被加载后,类的整个结构都会被封装在class对象中
动态的创建对象,通过反射:
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class c1 = Class.forName("reflection.User");
// User user = (User) c1.newInstance(); //本质调用无参构造器
// System.out.println(user);
//通过构造器构造对象
Constructor constructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
User user2 = (User) constructor.newInstance("秦疆", 001, 15);
System.out.println(user2);
//通过反射调用普通方法
User user3 = (User)c1.newInstance();
//通过反射获取一个方法
Method setName = c1.getDeclaredMethod("setName", String.class);
//invoke 激活 (对象,“方法的值”)
setName.invoke(user3,"66");
System.out.println(user3.getName());
//通过反射操作属性
User user4 = (User) c1.newInstance();
Field name = c1.getDeclaredField("name");
//不能直接操作私有属性,需要关闭程序的安全检测,属性或方法的setAccessible(True)
name.setAccessible(true);
name.set(user4,"菲菲2");
System.out.println(user4.getName());
通过反射获取注解的信息:
public class Test04 {
public static void main(String[] args) throws NoSuchFieldException {
Class<?> c1 = null;
try {
c1 = Class.forName("reflection.Student2");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
//获得注解value的值
Tablekkk tablekkk = c1.getAnnotation(Tablekkk.class);
String value = tablekkk.value();
System.out.println(value);
//获得类指定的注解
Field f = c1.getDeclaredField("name");
Filekkk annotation = f.getAnnotation(Filekkk.class);
System.out.println(annotation.columnName());
System.out.println(annotation.length());
System.out.println(annotation.type());
}
}
@Tablekkk("db_student")
class Student2{
@Filekkk(columnName = "db",type = "varchar",length = 3)
private String name;
@Filekkk(columnName = "db",type = "int",length = 10)
private int id;
@Filekkk(columnName = "db",type = "int",length = 10)
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student2() {
}
public Student2(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
@Override
public String toString() {
return "Student2{" +
"name='" + name + '\'' +
", id=" + id +
", age=" + age +
'}';
}
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Tablekkk{
String value();
}
//属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Filekkk{
String columnName();
String type();
int length();
}