Markus Appel
Markus Appel

Reputation: 3238

Instantiating type parameter and override method

I want to do something similar to Scala's wildcards for pattern matching, so I need to instantiate an object of type T that will always return true when calling the equals() - method.

I know this is kind of hacky, so if I would attempt to call any other function on this object my computer might as well burst into flames, the only thing that is important is equals().

What I have so far:

public void match(Object toMatch, Effect0 effect) {
   val bothNull = toMatch == null && value == null;

    val equals = toMatch != null && toMatch.equals(value);

    if(bothNull || equals) {
        effect.f();
    }
}

public static Object any() {
    return new Object() {
        @Override
        public boolean equals(Object o) {
            return true;
        }
    };
}

But I have to somehow lift any() into type T.

The usage would look like this:

myClass.match(new MyClass(any(), "foo", "bar", any()), () -> ...);

What's important is that I can't, for example, compare a Pair<String, Integer> with a Pair<Integer, String>. So that's why I need generics.

Is that possible?

Upvotes: 1

Views: 109

Answers (1)

GhostCat
GhostCat

Reputation: 140427

Simply spoken, you can't.

When you only have a generic T parameter, the is no way to create instances of that, see here for details. You can work around that, for example by passing instances of Class around, but that still means reflection, and the need for default constructors, or heuristics for which constructor to call.

But even when you could instantiate that T, you can't dynamically create an anonymous subclass for that.

Upvotes: 1

Related Questions