1

It is easy to define a method returning the same value as the argument:

class A {
    public static void main(String[]args) {
        Derived sth = new Derived();
        String x = sth.foo("hello");
        System.out.println(x);
        Derived resultTypeIsKnown = sth.foo(sth);  // <==== !!!
        System.out.println(""+resultTypeIsKnown);
    }
}
class Base {
    <T>T foo(T t)
    {
        return t;
    }
}
class Derived extends Base {
}

You see that the compiler knows that although foo() is declared in the Base class, the compiler knows that sth.foo(sth) returns an instance of the Derived class:

Derived derivedRatherThanBase = sth.foo(sth);

How do I declare that the return value is of the same class as the object whose method is called? (In particular, for a method that always returns this?)

Something like:

class Base {
    <?ThisClass?> bar() {
        return this;
    }
}

I can write

    <T>T getThis(T t)
    {
        return (T)this;
    }

but x.getThis(x) uses an extra argument and produces a warning.

UPDATE OMG, what they are doing in the "possible duplicate"... But I already have the base class, it's a descendant of Collection. In other words, it is required that class Base extends Collection and knows its class.

And the real life code where I want to know THISCLASS already is very complex.

UPDATE2 As to the XY problem, what I want is:

class MyVerySpecialCollectionBase extends ... {
    ...
    THISCLASS addAll(Collection items) { ... }
}
class MyExtendedVerySpecialCollection extends MyVerySpecialCollectionBase  {
    ...
}

// use: 
MyExtendedVerySpecialCollection x =
      new MyExtendedVerySpecialCollection(aLotOfArgs)
      .addAll(list1)
      .addAll(list2);

The proposed solution sounds too complex and even less acceptable than either (1) redefining addAll() in each derived class or (2) making x.addAll(list1).addAll(list2); a separate statement.

18446744073709551615
  • 16,368
  • 4
  • 94
  • 127

0 Answers0