在Java中,是否有一种方法可以向现有类添加字段和方法? 我的需求是我导入了一个类到我的代码中,我需要添加一些字段,这些字段由现有字段导出,并且需要它们的返回方法。 有没有办法做到这一点?
在Java中,是否有一种方法可以向现有类添加字段和方法? 我的需求是我导入了一个类到我的代码中,我需要添加一些字段,这些字段由现有字段导出,并且需要它们的返回方法。 有没有办法做到这一点?
您可以创建一个继承您希望添加功能的类的类:
```public class sub extends Original{
...
}
如果超类中没有getter方法,想要访问任何私有变量,可以将它们从“private”更改为“protected”,然后正常引用即可。
希望这能帮到你!
public class A {
private String name;
public A(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
public class B extends A {
private String title;
public B(String name, String title){
super(name); //calls the constructor in the parent class to initialize the name
this.title= title;
}
public String getTitle(){
return this.title;
}
public void setTitle(String title) {
this.title= title;
}
}
B
的实例可以访问 A
中的公共字段:B b = new B("Test");
String name = b.getName();
String title = b.getTitle();
更详细的教程请查看继承(Java教程 > 学习Java语言 > 接口和继承)。
编辑:如果类A
有如下构造函数:
public A (String name, String name2){
this.name = name;
this.name2 = name2;
}
然后在 B
类中你有:
public B(String name, String name2, String title){
super(name, name2); //calls the constructor in the A
this.title= title;
}
如果你要继承的类是final的,那么这些例子实际上并不适用。例如,你不能使用这种方法来扩展java.lang.String类。但是,还有其他方法,比如使用CGLIB、ASM或AOP进行字节码注入。
// Define new extension method
String.metaClass.goForIt = { return "hello ${delegate}" }
// Call it on a String
"Paul".goForIt() // returns "hello Paul"
// Create new property
String.metaClass.num = 123
// Use it - clever even on constants
"Paul".num // returns 123
"Paul".num = 999 // sets to 999
"fred".num // returns 123
我可以解释如何像Groovy一样做,但也许对于发帖者来说这太多了。如果他们愿意,我可以进行研究并解释。