Java语言基础 反射和注解

27 篇文章 0 订阅
6 篇文章 0 订阅

反射

反射第一步 获取类class对象

Class c1 = Class.forName("全类名")
Class c2 = 类名.class
Class c3 =对象.getClass()

** 获取Constructor构造器对象 成员变量 方法 **

Class<?> student = Class.forName("Student");
Constructor<?> constructor = student.getDeclaredConstructor();
//打开权限 暴力反射
constructor.setAccessible(true);

** 创建对象 赋值 运行**

Student o = (Student) constructor.newInstance();
o.setAge(11);
o.setName("11");
System.out.println(o);

System.out.println(Student.getINSTANCE()==o);

反射突破泛型限制

List<Integer> list = new ArrayList<>();

Class<? extends List> listClass = list.getClass();
Method add = listClass.getDeclaredMethod("add", Object.class);
Object invoke = add.invoke(list,"get");
System.out.println(invoke);
System.out.println(list);

通过反射在泛型为Integer的集合添加String类型数据

注解

自定义注解 :@interface
元注解 :注解中注解
注解解析

** 自定义注解类**

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MBook {
String name();
//默认值 99
int price() default 99;
}

解析注解小demo

public class test {
@Test
public void test1(){
//解析方法上的注解
try {
//获取class对象
Class<?> bookStore = Class.forName("BookStore");

//获取方法
Method m = bookStore.getDeclaredMethod("mybook");

System.out.println(m.isAnnotationPresent(MBook.class));
//判断方法上是否有注解
if (m.isAnnotationPresent(MBook.class)) {
//获取注解
MBook declaredAnnotation = m.getDeclaredAnnotation(MBook.class);
System.out.println(declaredAnnotation.price());
System.out.println(declaredAnnotation.name());
}
} catch (ClassNotFoundException | NoSuchMethodException e) {
e.printStackTrace();
}

}
}

class BookStore{
@MBook(name="雨天飞行",price = 199)
public void mybook() {
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

NoBug.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值