62,621
社区成员
发帖
与我相关
我的任务
分享
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Value
{
String[] value();
}
public class Test01
{
//私有属性
private int a = 0;
//私有方法
@Value(value = { "hello", "world" })
private int add(int b)
{
return a + b;
}
}
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Test02
{
public static void main(String[] args) throws Exception
{
// Class cls = Test01.class; 或者
Test01 tst = new Test01();
Class cls = Class.forName("Test01");
// 反射设置属性
Field field = cls.getDeclaredField("a");
field.setAccessible(true); //更改为可访问
field.setInt(tst, 10);
// 反射调用方法
Method method = cls.getDeclaredMethod("add", int.class);
method.setAccessible(true); //更改为可访问
int rst = (Integer) method.invoke(tst, 8);
System.out.println(rst);
// 反射取得方法的注解
Annotation[] anns = method.getAnnotations();
for (Annotation a : anns)
{
if (a instanceof Value)
{
String[] strs = ((Value) a).value();
System.out.println(strs[0] + "$" + strs[1]);
}
}
}
}