Is it possible to get a Object that is instanced in the Code by a String at Runtime?
Somthing like that:
public String xyz = "aaaa_bbb";
getObject("xyz").some function of String (e.g.: .split("_"))
Thanks
Here's an example
If it's a class field, you can get it by name like this.
import java.lang.reflect.Method;
public class Test {
public String stringInstance = "first;second";
public void Foo() {
try {
Object instance = getClass().getDeclaredField("stringInstance").get(this);
Method m = instance.getClass().getMethod("split", String.class);
Object returnValue = m.invoke(instance, ";");
if(returnValue instanceof String[])
{
for(String s : (String[])returnValue )
{
System.out.println(s);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String a[]){
new Test().Foo();
}
}
If it's a local method variable you are trying to invoke on, then you might be able to get at to the variable in from the current method from the call stack Thread.currentThread().getStackTrace()
maybe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With