一,注解示例
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String name() default "";
String value() default "小虎哥";
int age();
int id() default -1;
String[] schools() default {"西部开源", "清华大学"};
}
二、反射使用
2.1放射用到的类
java.lang.Class: 代表一个类
java.lang.reflect.Method:代表类的方法
java.lang.reflect.Field:代表类的成员变量
java.lang.reflect.Constructor:代表类的构造器
2.2反射获取类构造器对象
Class c3 = Student.class;
Class c1 = person.getClass();
Class c2 = Class.forName("com.kuang.reflection.Student");
Class c4 = Integer.TYPE;
2.3构造对象
Class c1 = Class.forName("。。。.User");
User user = (User)c1.newInstance();
Constructor constructor = c1.getDeclaredConstructor(String.class,int.class,int.class);
User user =(User) constructor.newInstance("name", 1, 18);
Method setName = c1.getDeclaredMethod("setName", String.class);
setName.invoke(user, "name");
Field name = c1.getDeclaredField("name");
name.setAccessible(true);
name.set(user, "name");
2.4反射获取泛型
public class Test11 {
public void test01(Map<String, User> map, List<User> list) {
System.out.println("test01");
}
public Map<String, User> test02() {
System.out.println("test02");
return null;
}
public static void main(String[] args) throws NoSuchMethodException {
Method method = Test11.class.getMethod("test01", Map.class, List.class);
Type[] genericParameterTypes = method.getGenericParameterTypes();
for (Type genericParameterType : genericParameterTypes) {
System.out.println("#" + genericParameterType);
if (genericParameterType instanceof ParameterizedType) {
Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArgument);
}
}
}
method = Test11.class.getMethod("test02", null);
Type genericReturnType = method.getGenericReturnType();
if (genericReturnType instanceof ParameterizedType) {
Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArgument);
}
}
}
}
2.5反射获取注解
public class Test12 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class c1 = Class.forName("类包路径");
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
MyAnnontation myAnnotation = (MyAnnontation ) c1.getAnnotation(MyAnnontation .class);
String value = myAnnotation.value();
System.out.println(value);
Field f = c1.getDeclaredField("id");
MyFieldAnnontation annotation = f.getAnnotation(MyFieldAnnontation.class);
}
}