java 通过字符串获取实例化对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5092972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:23:18  来源:igfitidea点击:

Get instanced object by String

javastringobjectfield

提问by user630447

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

谢谢

回答by Bala R

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.

如果它是您尝试调用的本地方法变量,那么您可能能够从调用堆栈中的当前方法中获取变量 Thread.currentThread().getStackTrace()

回答by Mugur

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

如果您只想从初始字符串中获取“aaaa”和“bbb”字符串,则可以使用StringTokenizer

回答by Stephen C

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 Mapclass.

但正如评论指出的那样,如果你真的想实现一个关联数组,那么在 Java 中有更好的方法来做到这一点;例如使用一个Map类。

回答by Riduidel

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

如果你的 String 是你对象的成员字段,你可以去看看这个Field类。

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
  1. 获取与 xyz 关联的 Field 对象
  2. 从其名称和参数列表中获取方法(用作示例Class#getDeclaredMethod(...)
  3. 在此特定实例上调用方法

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 !

所以,如果你有替代品,那就使用它吧!

回答by user630447

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.

我在 jPanel 上有自定义组件,我想在不重新绘制它们的情况下使用它们。我知道如果我使用列表或地图是可能的,但我必须更改地图中的值,然后使用地图中的信息重新绘制 GUI。