简体   繁体   English

Java:扩展Object类

[英]Java: extending Object class

I'm writing (well, completing) an "extension" of Java which will help role programming. 我正在编写(好,完成)Java的“扩展”,这将有助于角色编程。
I translate my code to Java code with javacc. 我用javacc将代码翻译成Java代码。 My compilers add to every declared class some code. 我的编译器为每个声明的类添加了一些代码。 Here's an example to be clearer: 这是一个更清晰的例子:

MyClass extends String implements ObjectWithRoles { //implements... is added
    /*Added by me */
    public setRole(...){...}
    public ...
    /*Ends of stuff added*/
    ...//myClass stuff
}

It adds Implements.. and the necessary methods to EVERY SINGLE CLASS you declare. 它为您声明的每个单一类添加了Implements ..和必要的方法。 Quite rough, isnt'it? 相当粗糙,不是吗?

It will be better if I write my methods in one class and all class extends that.. but.. if class already extends another class (just like the example)? 如果我在一个类中编写我的方法并且所有类都扩展了那个...但是..如果类已经扩展了另一个类(就像示例那样)会更好吗?

I don't want to create a sort of wrapper that manage roles because i don't want that the programmer has to know much more than Java, few new reserved words and their use. 我不想创建一种管理角色的包装器,因为我不希望程序员必须知道的不仅仅是Java,很少有新的保留字及其用法。

My idea was to extends java.lang.Object.. but you can't. 我的想法是扩展java.lang.Object ..但你不能。 (right?) (对?)
Other ideas? 其他想法?

I'm new here, but I follow this site so thank you for reading and all the answers you give! 我是新来的,但我关注这个网站,谢谢你的阅读和你给出的所有答案! (I apologize for english, I'm italian) (我为英语道歉,我是意大利人)

If it is only like a "research" project in which you want to explore how such extension would work, you could provide your own implementation of the Object class. 如果它只是一个“研究”项目,您想要探索这种扩展如何工作,您可以提供自己的Object类实现。 Simply copy the existing object implementation, add your setRole method etc, and give -Xbootclasspath:.:/usr/lib/jvm/java-6-sun/jre/lib/rt.jar as parameter to the java command. 只需复制现有的对象实现,添加setRole方法等,并将-Xbootclasspath:.:/usr/lib/jvm/java-6-sun/jre/lib/rt.jar作为java命令的参数。 (I will look for api-classes in . before looking in the real rt.jar .) (我将寻找API类中.寻找在现实面前rt.jar )。

  • you can extend Object - every class extends it. 你可以扩展Object - 每个类都扩展它。
  • you seem to need something like multiple inheritance - there isn't such a thing in Java 你似乎需要像多重继承这样的东西 - 在Java中没有这样的东西
  • if you want to add functionality, use object composition. 如果要添加功能,请使用对象组合。 Ie, 也就是说,

     YourClass extends Whatever implements ObjectWithRoles { private RoleHandler roleHandler; public RoleHandler getRoleHandler() {..} // defined by the interface } 

And then all of the methods are placed in the RoleHandler 然后所有方法都放在RoleHandler

You should consider using composition rather than inheritence to solve this problem; 你应该考虑使用组合而不是继承来解决这个问题; that way you can provide the functionality you need without using up your "one-shot" at inheritence. 通过这种方式,您可以提供所需的功能,而无需在继承中使用“一次性”。

For example, the JDK provides a class PropertyChangeSupport , which can be used to manage PropertyChangeListener s and the firing of PropertyChangeEvent s. 例如,JDK提供了一个类PropertyChangeSupport ,它可用于管理PropertyChangeListener和触发PropertyChangeEvent In situations where you wish to write a class that fires PropertyChangeEvent s you could embed a PropertyChangeSupport instance variable and delegate all method calls to that. 在您希望编写触发PropertyChangeEvent的类的情况下,您可以嵌入PropertyChangeSupport实例变量并将所有方法调用委托给它。 This avoids the need for inheritence and means you can supplement an existing class hierarchy with new functionality. 避免了对继承的需要,并且意味着您可以使用新功能补充现有的类层次结构。

public class MyClass extends MySuperClass {
  private final PropertyChangeSupport support;

  public MyClass() {
    this.support = new PropertyChangeSupport(this);
  }

  public void addPropertyChangeListener(PropertyChangeListener l) {
    support.addPropertyChangeListener(l);
  }

  protected void firePropertyChangeEvent() {
    PropertyChangeEvent evt = new ...
    support.firePropertyChangeEvent(evt);
  }
}

If you're talking about adding a role to all your objects I would also consider an annotation-based solution. 如果您正在谈论为所有对象添加角色,我还会考虑基于注释的解决方案。 You'd annotate your classes with something like @Role("User"). 你可以用@Role(“User”)之类的东西来注释你的类。 In another class you can extract that role value and use it. 在另一个类中,您可以提取该角色值并使用它。

I think it would need an annotation with runtime retention and you can check, run-time, whether the annotation is present using reflection and get that annotation using getAnnotation . 我认为它需要一个带有运行时保留的注释,你可以检查运行时是否使用反射存在注释并使用getAnnotation获取注释。 I feel that this would be a lot cleaner than extending all your classes automatically. 我觉得这比自动扩展所有类要清晰得多。

I believe there are some frameworks which use exactly such a solution, so there should be example code somewhere. 我相信有一些框架完全使用这样的解决方案,所以应该有一些示例代码。

If you are doing what you are doing, then inheritance is probably not the correct idiom. 如果你正在做你正在做的事情,那么继承可能不是正确的习惯用法。 You may want to consider the decorator pattern, whereby you construct a class that takes as its parameter some other class with less functionality, and adds some additional functionality to it, delegating to the existing class for functionality that already exists. 您可能需要考虑装饰器模式,从而构造一个类,该类将其他一些具有较少功能的类作为其参数,并为其添加一些附加功能,将现有类委托给已存在的功能。 If the implementation is common to many of your decorators, you may want to consider putting that functionality in class that can be shared and to which you can delegate for all your decorators. 如果实现对于许多装饰器是通用的,您可能需要考虑将该功能放在可以共享的类中,以及可以为所有装饰器委派的功能。 Depending on what you need, double-dispatch or reflection may be appropriate in order to make similar but not quite the same decorators for a large variety of classes. 根据您的需要,双重调度或反射可能是适当的,以便为各种类制作相似但不完全相同的装饰器。

Also, as has been pointed out in the comments, String is declared "final" and, therefore, cannot be extended. 此外,正如在注释中指出的那样,String被声明为“final”,因此无法扩展。 So, you should really consider a solution whereby you delegate/decorate objects. 因此,您应该考虑一个委托/装饰对象的解决方案。 For example, you might have some object that wraps a string and provides access to the string via getString() or toString(), but then adds the additional functionality on top of the String class. 例如,您可能有一些包装字符串的对象,并通过getString()或toString()提供对字符串的访问,但随后在String类之上添加了附加功能。

If you just want to associate some objects with additional attributes, use a Map (eg HashMap ). 如果您只想将某些对象与其他属性相关联,请使用Map (例如HashMap )。

What you really want to do would be monkey patching , ie changing the behaviour of existing classes without modifying their code. 你真正想要做的就是猴子修补 ,即改变现有类的行为而不修改他们的代码。

Unfortunately, Java does not support this, nor things like mixins that might be used alternatively. 不幸的是,Java不支持这一点,也不支持可能使用的mixin So unless you're willing to switch to a more dynamic language like Groovy, you'll have to live with less elegant solutions like composition. 因此,除非你愿意转换到像Groovy这样更具动态性的语言,否则你将不得不忍受像组合这样不那么优雅的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM