How to call a method with generic parameter of a self referencing generic interface in JAVA?

1 day ago 1
ARTICLE AD BOX

Ignore for a moment the generic nature of the types involved. An expression serving as the argument to a method with signature

void genericMethod(SelfReferenceClass obj)

must have a type assignable to SelfReferenceClass. Expressions of type ISelfReferenceInterface<SelfReferenceClass> do not satisfy that requirement. That the class of the object referenced by your argInterface is such a type doesn't factor in.

This is the same issue as you have with:

Serializable s = new String("123"); Integer i = Integer.valueOf(s); // rejected

The method Integer.valueOf(String) is not applicable to an expression of type Serializable, even if that expression evaluates to a reference to an object of class String.


is there any way to make #18 pass compile?

It's unclear what sort of changes would be acceptable to you, but one way would be to modify ISelfReferenceInterface like so:

public interface ISelfReferenceInterface<S extends ISelfReferenceInterface<S>> { public void genericMethod(ISelfReferenceInterface<S> obj); }

, and to make the corresponding change to SelfReferenceClass. Then your #18 should compile as-is. Note, however, that the resulting method will accept arguments of more types and more classes than your original one does. For instance, consider this class:

public class AnyOldClass implements ISelfReferenceInterface<SelfReferenceClass> { @Override public void genericMethod(SelfReferenceClass obj) { System.out.println("This is generic method in" + getClass().getSimpleName()); } }

If you widen the type of the argument to ISelfReferenceInterface.genericMethod() as described above, then instances of AnyOldClass will be type-correct arguments to ISelfReferenceInterface<SelfReferenceClass>.genericMethod() and SelfReferenceClass.genericMethod(). That may not be consistent with your intent.

A relevant point to take from all this is that an interface being self-referential in the way you present does not force its implementations to be self-referential in an analogous way.

Read Entire Article