1

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?

Markus Appel
  • 3,138
  • 1
  • 17
  • 46
  • 1
    where does `value` come from? – jwismar Jan 22 '19 at 13:20
  • @jwismar Sorry, it's because `MyClass` actually is a wrapper object. – Markus Appel Jan 22 '19 at 13:21
  • 1
    In your examples there is no usage of T ... you only have that in your description. Can you give a more complete example that includes where/how that T comes in, and in which ways you would want to use that? – GhostCat Jan 22 '19 at 13:27
  • you can't create an instance of `T` when you don't know it; you would need a `Class clazz` as parameter, and create an instance via `clazz.getConstructor().newInstance();` (of course might break if such a constructor is not present). The problem you will face after this is that you need to override `equals`, so you would need an anonymous inner class, created at runtime, I don't think this is possible via reflection. Probably a dynamic proxy could solve this, but I have not tried this yet – Eugene Jan 22 '19 at 13:28
  • I appreciate the quick comeback ;-) – GhostCat Jan 28 '19 at 11:42

1 Answers1

1

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.

GhostCat
  • 137,827
  • 25
  • 176
  • 248