Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get instanced object by String

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

like image 640
user630447 Avatar asked Feb 23 '11 15:02

user630447


1 Answers

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.

like image 91
Bala R Avatar answered Oct 12 '22 11:10

Bala R