我正在使用Java在大学里做我的项目,我被困给变量赋值。在我的课堂上,我很少有没有价值观的领域。但是,每次调用类构造函数时,我想为从数据库中读取变量提供值。现在,例如,我的班级中有7个字段,并且根据执行情况,将仅使用一个字段,现在我想在运行时将值分配给该字段。意思是,如果只有两个字段可以使用,那么我只想为这两个字段赋值。我将从数据库中获取具有值的字段名称,因此我将检查字段名称是否匹配,然后将值分配给变量。或者,如果还有其他值可以处理。
下面给出的代码不起作用,语法错误
谢谢您的投入。
package RandD;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
public class Reflection {
public static final String field1="";
static final int field2=0;
private final String field3="";
static String field4="";
protected String field5="";
List<String> element1;
HashMap<String, Integer> element2;
public Reflection() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{
test();
}
public static void main(String arg[]) throws NoSuchFieldException, SecurityException{
new Reflection().test();
}
public void test() throws NoSuchFieldException, SecurityException{
Field[] field = Reflection.class.getDeclaredFields();
for(Field fd:field){
if(fd.getName().equalsIgnoreCase("field3")){
fd.getName()="Hello World";
}
}
}
}
尽管您可以通过反射访问和修改私有变量,但还是要谨慎使用。
设置私有字段的示例代码。
import java.lang.reflect.*;
public class ReflectionDemo{
public static void main(String args[]){
try{
Field[] fields = A.class.getDeclaredFields();
A a = new A();
for ( Field field:fields ) {
field.setAccessible(true);
if(field.getName().equalsIgnoreCase("name")){
field.set(a, "StackOverFlow");
System.out.println("A.name="+field.get(a));
}
if(field.getName().equalsIgnoreCase("age")){
field.set(a, 20);
System.out.println("A.age="+field.get(a));
}
if(field.getName().equalsIgnoreCase("rep")){
field.set(a,"New Reputation");
System.out.println("A.rep="+field.get(a));
}
if(field.getName().equalsIgnoreCase("count")){
field.set(a,25);
System.out.println("A.count="+field.get(a));
}
}
}catch(Exception err){
err.printStackTrace();
}
}
}
class A {
private String name;
private int age;
private final String rep;
private static int count=0;
public A(){
name = "Unset";
age = 0;
rep = "Reputation";
count++;
}
}
输出:
java ReflectionDemo
A.name=StackOverFlow
A.age=20
A.rep=New Reputation
A.count=25
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句