我正在开发一个 Eclipse RCP 应用程序,我最近开始在其中使用 Groovy。所以我 99% 的代码仍然是 Java。
我读到可以使用 Groovy 覆盖方法并将方法添加到 Java 类中,我能够通过将方法添加到 java.lang.String 中来对此进行测试。
但这仅在我在 Groovy 类中使用字符串时有效。被覆盖的方法不被视为在 Java 类中被覆盖。
这是一些代码:
/*
* This is a Java class
*/
public class CTabItem {
...
private API
...
public void setControl(Control control){
private API
}
}
/*
* This is also a Java class
*/
public class Control {
...
private API
...
}
/*
* This is also a Java class
*/
public class OtherClass {
...
private API
...
private void someMethodIDontKnow(){
Control control = new Control();
CTabItem tab = new CTabItem();
tab.setControl(control);
}
}
/*
* This is a Groovy class
*/
public class MyViewPart extends org.eclipse.ui.part.ViewPart {
....
public void createPartControl(Composite parent) {
/* parent (or the parent of parent) is a Control
which is set somewhere in a CTabItem to which
I don't get access */
}
}
我需要从控件中获取选项卡。但由于实例化 MyViewPart 的不是我,而是一些私有(private) API,因此我无权访问它。 Groovy 可以为我做些什么吗?欢迎任何建议或代码。谢谢!
最佳答案
简短的回答是:不,如果创建对象和调用方法的代码是纯 Java(即非 Groovy)代码,那是不可能的。 Groovy 通过拦截对对象(Java 对象和 Groovy 对象)的所有方法调用并使用它的 ExpandoMetaClass 来发挥它的魔力。添加行为。但是,它不能改变纯 Java 代码如何确定在纯 Java 类上调用哪个方法。要查看,请运行以下示例代码:
// UseTheString.java (a pure Java class)
public class UseTheString {
public static void main(String[] arg) {
String s = "Hello world";
System.out.println(s);
System.out.println(s.substring(1));
ModifyStringClass.messWithMetaClasses(s);
System.out.println(s.substring(1));
}
}
和
// ModifyStringClass.groovy (a Groovy class)
class ModifyStringClass {
public static messWithMetaClasses(String t) {
java.lang.String.metaClass.substring = { int n -> "!" }
println(t.substring(1))
}
}
你会得到输出:
Hello world
ello world
!
ello world
如您所见,如果从其他 Groovy 代码调用 Groovy 可以覆盖纯 Java 对象上的方法,但它不能改变 Java 代码使用它的方式。
关于java - 当 Java 类未在我的代码中实例化时,是否可以使用 Groovy 覆盖 Java 类中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15884190/