Java:向现有Class添加字段和方法?

在Java中,是否有一种向现有类添加一些字段和方法的方法? 我想要的是我有一个类导入到我的代码中,我需要添加一些从现有字段派生的字段及其返回方法。 有没有办法做到这一点?

您可以创建一个类,将您希望添加function的类扩展到:

public class sub extends Original{ ... } 

要访问超类中的任何私有变量,如果没有getter方法,可以将它们从“private”更改为“protected”并能够正常引用它们。

希望有所帮助!

您可以使用Java扩展类。 例如:

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

有关更详细的教程,请参阅inheritance(Java教程>学习Java语言>接口和inheritance) 。

编辑:如果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; } 

如果您要扩展的类不是最终的,那么这些示例才真正适用。 例如,您无法使用此方法扩展java.lang.String。 然而,还有其他方法,例如使用CGLIB,ASM或AOP使用字节代码注入。

假设这个问题是在询问C#扩展方法或JavaScript原型的等价物,那么从技术上讲,Groovy可以做很多事情。 Groovy编译Java并且可以扩展任何Java类,甚至是最终的Java类。 Groovy有metaClass来添加属性和方法(原型),例如:

 // 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那样做,但也许这对海报来说太过分了。 如果他们喜欢,我可以研究和解释。