Java – a technique for extending classes using private constructors

Is there a standard technique to "extend" classes with private constructors, like most singleton classes? Specifically, I'm trying to extend Java lang.management. Threadinfo class, because I add a lot of them to HashSet to control uniqueness However, the way I determine whether two threads are equal is different and different from the default implementation of the equals () method

In this case, the extension class is obviously not an option

Is it reasonable to make a wrapper class similar to accepting threadinfo in the constructor, then manually fill in all relevant fields with values, and then override equals () and hashcode (), or is there a better way to do this?

Things like me are what I started to write, but better realization is ideal:

class ThreadInfoWrapper {

    private ThreadInfo info;
    ThreadInfoWrapper(ThreadInfo info) {
        this.info = info;
    }

    //Populate instance variables with Thread.State,thread ID,etc.. with
    //Getters/setters and all that other stuff

    public boolean equals(Object o) { //Unique implementation
    }

    public int hashCode() { //Whatever implementation
    }

}

But it feels like a very circuitous way to achieve some basic functions I investigated that there is no implementation of collections using custom comparators in the Java standard library I think I can write my own hash set implementation, but this is too much for a simple case Any insight will help

Solution

By extension, you mean how to create derived classes that use private constructors as their superclass constructors You can't. They are private to prevent you from doing so Since JRE courses are written by competent programmers, there are good reasons Therefore, even if you can use spoofing (such as reflection or bytecode operation) to solve it, you should not do so

But everything is @ R_ 419_ 1844@. Anyway, you should prefer combinatorial inheritance Decorator and proxy design patterns can be useful (your examples are close to these)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>