学习内容:
1、 默认你已经掌握了反射的基础 直接看代码例子!
package com.liu.reflection;
import java.lang.annotation.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
public class Test07 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
Class<?> cl = Class.forName("com.liu.reflection.Student");
Annotation[] annotations = cl.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println("annotation = " + annotation);
}
ClassLms annotation = cl.getAnnotation(ClassLms.class);
String value = annotation.value();
System.out.println("value = " + value);
Field name = cl.getDeclaredField("name");
PropertyLms annotation1 = name.getAnnotation(PropertyLms.class);
System.out.println("annotation1.columName() = " + annotation1.columName());
System.out.println("annotation1.type() = " + annotation1.type());
System.out.println("annotation1.length() = " + annotation1.length());
Method method = cl.getDeclaredMethod("study", String.class);
MethodLms methodLms = method.getAnnotation(MethodLms.class);
System.out.println("methodLms.value() = " + methodLms.value());
Type[] genericParameterTypes = method.getGenericParameterTypes();
for (Type genericParameterType : genericParameterTypes) {
System.out.println("genericParameterType = " + genericParameterType);
}
}
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface ClassLms {
String value();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface PropertyLms {
String columName();
String type();
int length();
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface MethodLms {
String value();
}
@ClassLms("tbl_student")
class Student {
@PropertyLms(columName = "tbl_id", type = "int", length = 3)
private int id;
@PropertyLms(columName = "tbl_name", type = "varchar", length = 20)
private String name;
@PropertyLms(columName = "tbl_age", type = "int", length = 3)
private int age;
public Student() {
}
@MethodLms("study")
public void study(String str) {
System.out.println(str + "学生正在努力学习!");
}
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}