通过String获取实例化对象

发布于 2024-10-18 20:52:33 字数 178 浏览 0 评论 0 原文

是否可以在运行时通过字符串获取代码中实例化的对象?

类似这样的:

public String xyz = "aaaa_bbb";

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

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

梓梦 2024-10-25 20:52:33

这是一个例子

如果它是一个类字段,你可以像这样通过名称来获取它。

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();
    }



}

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

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.

客…行舟 2024-10-25 20:52:33

很难弄清楚你在问什么,但你可以使用反射按名称获取字段值。像这样的事情:(

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

我省略了很多异常处理...)

但是正如评论指出的那样,如果您真的想实现关联数组,那么在 Java 中有更好的方法;例如使用 Map 类。

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.

不语却知心 2024-10-25 20:52:33

你可能需要重新表述这个问题。

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

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

蘸点软妹酱 2024-10-25 20:52:33

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

但是,我必须警告您,您最终得到的代码将比您在这里预期的要长得多。事实上,您必须执行一些操作:

  1. 从其名称和参数列表中获取与 xyz Get 方法关联的字段对象
  2. (使用 Class#getDeclaredMethod(... ))
  3. 在此特定实例上调用方法

每个步骤都会产生一行相当晦涩的代码,并抛出一堆异常。

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

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 !

烟燃烟灭 2024-10-25 20:52:33

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文