双11狂欢大促

盲盒赢 定制羽绒服

开启惊喜盲盒,抽取你的专属好礼

— 惊喜奖品抢先看 —

关于java中利用反射获取注解对象为enum的问题 弄两天了 谁有办法?

HelloWorld990632303 HelloWorld990632303 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
定义注解AnnotationTest2:
package com.anotation;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationTest2
{
String value();
public a2 v2();

}
enum a2
{
when,where,what;
}
定义类和方法Test2并且使用上面定义的注解:
package com.anotation;

public class Test2
{
@AnnotationTest2(value = "hello",v2 = a2.what)
public void method1()
{
System.out.println("method1");
}
public static void main(String[] args)
{
Test2 test = new Test2();
test.method1();

}

}
定义反射MyReflection获取注解:
package com.anotation;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Method;
import java.lang.Exception;
public class MyReflection
{
public static void main(String[] args) throws Exception
{
Test2 test = new Test2();
Class<Test2> classType = Test2.class;

Method method = classType.getMethod("method1", new Class[]{});

method.setAccessible(true);

if(method.isAnnotationPresent(AnnotationTest2.class))
{
method.invoke(test, new Object[]{});
AnnotationTest2 annotation = method.getAnnotation(AnnotationTest2.class);

String hello = annotation.value();
a2 what = annotation.v2().what;
System.out.println(hello + what);

}



}



}
下面是遇到的问题,高手指教!
method1
Exception in thread "main" java.lang.IllegalAccessError: tried to access class com.anotation.a2 from class com.sun.proxy.$Proxy1
at com.sun.proxy.$Proxy1.v2(Unknown Source)
at com.anotation.MyReflection.main(MyReflection.java:23)

...全文
评论 2
收藏 已收藏
分享
返回顶部
HelloWorld990632303
Java SE 62,621 成员 307,251 内容