
因为静态只能接收静态,反射获得的值是静态的。
例如:
public class Test{
public static void main(String[] args) {
aaa();
int n = num;
}
int num =100;
public void aaa(){}
}
aaa()和num会被强制转为static类型;
可以这样:
public static void main(String[] args) {
Test test = new Test();//实例化
test aaa();
int n = test num;
}
// 定义注解并指定java注解保留策略为运行时RUNTIME,运行时注入到JAVA字节码文件里
// 这样才可以在运行时反射并获取它。
@javalangannotationRetention(javalangannotationRetentionPolicyRUNTIME)
@interface MyAnnotation{
String key() default "";
int value() default 0;
}
// 使用注解
@MyAnnotation(key="key1",value=200)
class MyClass{}
// 反射注解
public static void main(String[] args){
MyClass myClass=new MyClass();
MyAnnotation annotation=myClassgetClass()getAnnotation(MyAnnotationclass);
Systemoutprintln("key="+annotationkey()+"\tvalue="+annotationvalue());
}
以上就是关于java中利用反射为变量赋值的时候,为什么变量需要声明为static的全部的内容,包括:java中利用反射为变量赋值的时候,为什么变量需要声明为static的、java反射机制 怎样获取到类上面的注解、等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)