Technique for extending a class with private constructors

安稳与你 提交于 2019-12-05 11:15:29

By extended, you mean how to create derived classes, which make use of the private constructor as their super class constructor. You can't, they were made private to prevent you doing that. As the JRE classes were written by competent programmers, there will be good reasons for this. So even if you could work around it using trickery, such as reflection or bytecode manipulation, you should not do so.

But all is not lost. You should anyway prefer composition to inheritance. The Decorator and Proxy design patterns can be useful (your example is close to these).

I think what you are doing is reasonable given that there are few other options.

An alternative might be to write your own subclass of HashMap that uses your "special" equals instead of the default. (There may already be apache or guava implementations to do this - anybody know offhand?)

(added later)

Because I'm lazy, and because ThreadInfo has all getters so it's fairly "safe" to expose, I'd be tempted to make the wrapper class very simple, with no getters nor setters:

public class ThreadInfoWrapper {

// public so an outsider can get at the wrapped ThreadInfo 
// could be private if you are sure that will never be necessary
public final ThreadInfo threadInfo;

public ThreadInfoWrapper(ThreadInfo threadInfo) {
  this.threadInfo = threadInfo;
}

public boolean equals(Object o) { //Unique implementation
  // refer to threadInfo.blah...
}

public int hashCode() { //Whatever implementation
  // refer to threadInfo.blah...
}

}

However, this depends on just what info you are using for your equals and hashcode.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!