1

I couldn't event choose right words for the question.

I have a class and a factory method.

class MyObject<Some, Other> {

    static <T extends MyObject<U, V>, U, V> T of(
            Class<? extends T> clazz, U some, V other) {
        // irrelevant 
    }

    private Some some;

    private Other other;
}

Now I want to add two more factory methods each which only takes U or V.

That would be look like this. That means those omitted V, or U remains unset(null).

static <T extends MyObject<U, ?>, U> T ofSome(
        Class<? extends T> clazz, U some) {
    // TODO invoke of(clazz, some, @@?);
}

static <T extends MyObject<?, V>, V> T ofOther(
        Class<? extends T> clazz, V other) {
    // TODO invoke of(clazz, @@?, other);
}

I tried this but not succeeded.

static <T extends MyObject<U, ?>, U> T ofSome(
        final Class<? extends T> clazz, final U some) {
    return of(clazz, some, null);
}

Compiler complains with following message.

no suitable method found for of(java.lang.Class,U, <nulltype>)

What is the right way to do it?

Jin Kwon
  • 20,295
  • 14
  • 115
  • 184
  • Please show the exact code : you don't declare return types in some of your methods. As a side note, in your first class U and V are distinct types according to the scope : class or instance since you declare it twice. – davidxxx Jun 26 '19 at 06:25
  • Try casting `null` to the required type, EG: `(V) null`... – Usagi Miyamoto Jun 26 '19 at 06:26

1 Answers1

2

You still need the generic parameter V, you just don't need the method parameter V.

static <T extends MyObject<U, V>, U, V> T ofSome(
        final Class<? extends T> clazz, final U some) {
    return of(clazz, some, null);
}

You need V in ofSome so that the compiler can infer the V type for of by looking at the type of clazz.

Sweeper
  • 213,210
  • 22
  • 193
  • 313