import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
//自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface GetMapping{//GetMapping.java-->GetMapping.class
String value() default "";
}
//接口定义
interface RemoteService{
@GetMapping("/service/hello")
String call(String msg);
}
public class AnnotationTests {
public static void main(String[] args) throws NoSuchMethodException {
//1.反射的入口
Class<RemoteService> remoteServiceClass = RemoteService.class;
//2.获取方法对象
Method call =
remoteServiceClass.getDeclaredMethod("call", String.class);
//3.获取方法对象上的注解
GetMapping annotation = call.getAnnotation(GetMapping.class);
//4.获取注解中value属性
String value=annotation.value();
System.out.println(value);
}
}
Java中的反射原理代码
最新推荐文章于 2022-08-18 09:03:07 发布