Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've a list of strings, field names, of a class in a loop from resource bundle. I create an object and then using loop i want to set values for that object. For example, for object

Foo f = new Foo();

with parameter param1, I have string "param1" and I somehow want to concate "set" with it like "set"+"param1" and then apply it on f instance as:

f.setparam1("value");

and same for getter. I know reflection will help but I couldn't manage to do it. Please help. Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
552 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can do something like this. You can make this code more generic so that you can use it for looping on fields:

Class aClass = f.getClass();
Class[] paramTypes = new Class[1];
paramTypes[0] = String.class; // get the actual param type

String methodName = "set" + fieldName; // fieldName String
Method m = null;
try {
    m = aClass.getMethod(methodName, paramTypes);
} catch (NoSuchMethodException nsme) {
    nsme.printStackTrace();
}

try {
    String result = (String) m.invoke(f, fieldValue); // field value
    System.out.println(result);
} catch (IllegalAccessException iae) {
    iae.printStackTrace();
} catch (InvocationTargetException ite) {
    ite.printStackTrace();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...