通过字符串获取实例对象 [英] Get instanced object by String

查看:105
本文介绍了通过字符串获取实例对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在运行时获取代码中由字符串实例化的对象?

Is it possible to get a Object that is instanced in the Code by a String at Runtime?

类似的东西

public String xyz = "aaaa_bbb";

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

谢谢

推荐答案

以下是示例

如果它是一个类字段,则可以通过这样的名称来获取它.

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



}

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

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.

这篇关于通过字符串获取实例对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆