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

HelloWorld990632303 2013-10-28 03:41:11
定义注解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)

...全文
190 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
samueltango 2014-06-27
  • 打赏
  • 举报
回复
把enum定义放到注解里面即可,代码如下:
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationTest2
{
	String value();
	public a2 v2();

	enum a2
	{
		when,where,what;
	}
}
代码中引用enum时用全名AnnotationTest2.a2
圣斗士小强 2013-10-28
  • 打赏
  • 举报
回复
你应该讲enum单独写成一个类,放在一个类文件中并且用public修饰,这样就可以通过测试了。例如: public enum a2{ when,what,where; } 这样就可以了^_^

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧