I am doing my project in university using java, I have got stuck to assign value to variable. In my class I have few fields without values. However, I want to provide value to variable reading from database each time when class constructor is called. Now, there are 7 fields in my class for example and from that there will be use of only one field based on execution, now I want to assign value to that field(s) at run time. Means, if there is only two field which will be used then I want to assign value to only those two fields. I will get the field name from database with value, so I will check if the field name is matching then I will assign the value to variable. OR if there is any other value to handle this.
Below given code is not working, syntax error
I would appreciate your inputs.
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";
}
}
}
}
Aucun commentaire:
Enregistrer un commentaire