神奇地调用Java中的方法
有没有某种方法可以在 Java 中使用魔法方法,就像在 PHP 中使用 __call
一样?
例如:
class foo {
@Setter @Getter
int id;
@Getter
Map <String, ClassInFoo> myMap;
protected class ClassInFoo {
@Setter @Getter
String name;
}
@Setter
String defaultKey;
}
我对 getter 和 setter 方法使用 Project Lombok 注释来简化代码。
让我们考虑一下,我的映射包含由 String 映射的多个项目,并且 defaultKey 定义默认项目。
我希望能够调用 foo.getName() ,它将返回默认名称为 foo.myMap.get(defaultKey).getName() 。
我不能手动编写所有 getter 的原因是 Foo 类实际上是通过泛型继承的,并且内部类可能不同。
我有点需要这样的东西:
function Object __call(method) {
if (exist_method(this.method)
return this.method();
else
return this.myMap.get(defaultKey).method();
}
这在 Java 中是否可能?
编辑:
我在这里做了一个更精确的例子来说明我想要实现的目标:https:// /gist.github.com/1864457
这样做的唯一原因是“简写”内部类中的方法。
Is there some way of using magic methods in Java like there is in PHP with __call
?
For instance:
class foo {
@Setter @Getter
int id;
@Getter
Map <String, ClassInFoo> myMap;
protected class ClassInFoo {
@Setter @Getter
String name;
}
@Setter
String defaultKey;
}
I'm using Project Lombok annotations for getter and setter methods to simplify the code.
Let's consider that that my map contains several items mapped by String and the defaultKey defines the default one.
What I would like is to be able to call foo.getName()
which would return the default name as foo.myMap.get(defaultKey).getName()
.
The reason I can't just write all the getters manually is that the Foo class is in fact inherited with generics and the the inner class might be different.
I sort of need something like:
function Object __call(method) {
if (exist_method(this.method)
return this.method();
else
return this.myMap.get(defaultKey).method();
}
Is this somehow possible in Java?
EDIT:
I made a more precise example of what I am trying to achieve here: https://gist.github.com/1864457
The only reason of doing this is to "shorthand" the methods in the inner class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您绝对可以通过 reflection 使用其类似的功能
来查看是否可以使用类定义了一些方法,但我不明白如何通过正确使用接口、继承和重写方法来解决您的问题
提供反射等功能来管理某些无法解决的问题,但Java不是PHP,所以你应该尽量避免使用它有可能,因为它不属于该语言的哲学。
You absolutely can through reflection by using its features like
that can be used to see if a class has some methods defined but I don't see how your problem couldn't be solved with a proper use of interfaces, inheritance and overriding of methods
Features like reflection are provided to manage certain, otherwise unsolvable, issues but Java is not PHP so you should try to avoid using it when possible, since it's not in the philosophy of the language.
这不就是继承和重写的全部意义吗?
基类:
子类:
Isn't it the whole point of inheritance and overriding?
Base class:
Subclass: