Get instanced object by String

扶醉桌前 提交于 2020-01-01 05:42:07

问题


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


回答1:


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.




回答2:


You might have to rephrase the question.

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




回答3:


It is hard to make out what you are asking, but you can fetch field values by name using reflection. Something like this:

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

(I've left out a lot of exception handling ...)

But as a comment points out, if you are really trying to implement an associative array, there are better ways of doing this in Java; e.g. using a Map class.




回答4:


If your String is a member field of your object, you can go take a look at the Field class.

However, I have to warn you that the code that you'll end up with will be by far longer than what you expect here. Indeed, you'll have to do some operations :

  1. Get the Field obejct associated to xyz
  2. Get method from its name and parameters list (using as an example Class#getDeclaredMethod(...))
  3. Invoke the method on this particular instance

Each of these steps will eb a rather obscure line of code, with a bunch of throwed exceptions.

So, if you have an alternative, well, use it !




回答5:


I have custom components on a jPanel and i would like to work with them without repainting them. I knwo if i use a List or Map that it is possible but i have to change the value in the Map and then repaint the GUI with the infomration in the Map.



来源:https://stackoverflow.com/questions/5092972/get-instanced-object-by-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!