通过String获取实例化对象
是否可以在运行时通过字符串获取代码中实例化的对象?
类似这样的:
public String xyz = "aaaa_bbb";
getObject("xyz").some function of String (e.g.: .split("_"))
谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是一个例子
如果它是一个类字段,你可以像这样通过名称来获取它。
如果您尝试调用的是本地方法变量,那么您也许可以从调用堆栈
Thread.currentThread().getStackTrace()
中的当前方法中获取该变量。Here's an example
If it's a class field, you can get it by name like this.
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.很难弄清楚你在问什么,但你可以使用反射按名称获取字段值。像这样的事情:(
我省略了很多异常处理...)
但是正如评论指出的那样,如果您真的想实现关联数组,那么在 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:
(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.你可能需要重新表述这个问题。
如果您只想从初始字符串中获取“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
如果你的String是你的对象的成员字段,你可以去看看
Field
类。但是,我必须警告您,您最终得到的代码将比您在这里预期的要长得多。事实上,您必须执行一些操作:
Class#getDeclaredMethod(... )
)每个步骤都会产生一行相当晦涩的代码,并抛出一堆异常。
所以,如果你有替代方案,那就使用它吧!
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 :
Class#getDeclaredMethod(...)
)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 !
我在 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.