Get instant String object

Is it possible to get the object that is specified in the code as a string at runtime?

Something like that:

public String xyz = "aaaa_bbb";

getObject("xyz").some function of String (e.g.: .split("_"))

thank

+3
source share
5 answers

Here is an example

If this is 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 this is a local variable of the method you are trying to connect to, then you may be able to jump to the variable from the current method from the call stack Thread.currentThread().getStackTrace().

+5
source

You may need to rephrase the question.

If you just want to get the strings "aaaa" and "bbb" from the source string, you can use StringTokenizer

0
source

, , , . - :

    Class c = this.getClass();  // or Someclass.class
    Field f = c.getDeclaredField("xyz");
    String value = (String) f.get(this);
    ... = value.split("_");

( ...)

, , , Java ; Map.

0

, Field.

, , , , , . , :

.

, , , !

0
source

I have custom components on jPanel and I would like to work with them without redrawing them. I know if I use a list or map that this is possible, but I have to change the value on the map, and then redraw the GUI with the information on the map.

-1
source

Source: https://habr.com/ru/post/1794163/


All Articles