3

Okay this is my first post here so bear with me.. I'm working on a small side project about genetic programming and I'm using generics.

These are small code snippets:

public class BinaryGenome<C extends BinaryEncodeable<C>> {

    public BinaryGenome(C encodable){
        setGenome(encodable.encode());
        setSpecification(encodable);
    }

    public BinaryGenome(BitSet encoding) {
        setGenome(encoding);
        //What comes here???
    }
}

public interface BinaryEncodeable<C extends BinaryEncodeable<C>> {

    public BitSet encode();

    public C decode(BitSet encoding);

}

The BinaryGenome represents a genome, it contains the object it represents and the bit representation. I'm able to use the first constructor, but I'm having troubles with the second one. Is it possible to create an object C in the second constructor from the encoding, given that each class implementing BinaryEncodable has a decode method.

I know "new C()" doesn't work because of type errasure but is there some kind of factory I can use?

1 Answer 1

1

You could pass a supplier as an argument:

public BinaryGenome(BitSet encoding, Supplier<C> supp) {
    setGenome(encoding);
    C c = supp.get();
    //...
}
BinaryGenome<SomeClass> bg = new BinaryGenome<>(encoding, SomeClass::new);

But really, the decode method is better as a static factory method on SomeClass.

class SomeClass implements BinaryEncodeable<SomeClass> {
    public static SomeClass decode(BitSet encoding) {...}
}
BinaryGenome<SomeClass> bg = new BinaryGenome<>(SomeClass.decode(encoding));

Both scenarios require you to know the specific subtype anyways.

The second one even allows you to get rid of the type parameter.


The reason why BinaryGenome can't just construct an object of type C, is a lack of information.

At runtime, due to erasure, the only type BinaryGenome knows is BinaryEncodable and BinaryEncodable knows nothing about it's own subclasses.

Without an instance of C that holds this kind of information, there is no way for BinaryGenome to know what decode method to call.

Sign up to request clarification or add additional context in comments.

1 Comment

Alright thanks, I think I'll go with the supplier since the second constructor will be called from another BinaryGenome<C> object, which again doesn't know which static method to call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.