Resolving hidden Type Parameter in Java

69 Views Asked by At

Consider the following code:

class Scratch<T> {
  class InnerClass<T> {
    public void executeHiddenMethod(){
     //..some code to use Inner (T) type
     T r = null; //declared T from inner T type
     //..some code to use Outer (T) type
     //?? How to use outer T type?
    }
  }


//when trying to invoke the code:
public static void main(String[] args) {
    Scratch<String> scr = new Scratch<>();
    Scratch<String>.InnerClass<Double> d = scr.new InnerClass<>();
    d.executeHiddenMethod();
  }
}
  • Is there any way to reveal the Hidden Type Parameter of the Outer Class Scratch into the inner class InnerClass?
  • Or is there any clause in JLS that forbids this exposure in case of type parameters that get hidden?
1

There are 1 best solutions below

0
radof On

Unless I misunderstood the question, you should be able to use a different type parameter for the outer and inner class. T for Scratch and S for InnerClass.

 class Scratch<T> {
      class InnerClass<S> {
        public void executeHiddenMethod(){
         ...
         S s = null; 
         ...
         T t = null;
        }
      }
}