Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics return holder object from a generic method

Tags:

java

generics

In the following:

public interface SomeInteface<A, B> {  
    public B doSomething(A a);  
} 

I want to implement a version where the method doSomething returns the parameter a back.
I tried a Holder class;

class Holder<A> {  
     public A value;  
     public(A a){this.value = a;}  
}

and return Holder. However, I am not sure how to define an implementation class of SomeInterface so that I am able to do this.

The following does not even compile:

public class SomeImplementation<X> implements SomeInterface<T> {  

  private class Holder<A> {  
    public A value;  

    public class Holder<A>{  
      public A value;  
      public(A a){this.value = a;}  
    } 
  }   

  class Implementation<A, Holder<A>> implements SomeInterface<A, Holder<A>>{    
    public Holder<A> doSomething(A a){  
      //do stuff      
      return new Holder(a);  
    }   
  }      
}       

What am I messing up here?

like image 607
Cratylus Avatar asked Sep 30 '26 02:09

Cratylus


2 Answers

It needs to be

class Implementation<A> implements SomeInteface<A, Holder<A>>{    
          public Holder<A> doSomething(A a){  
              //do stuff  
              return new Holder<A>(a);  
          }     

   } 

In the classname you define the generic variables and their constraints. You don't need a Holder variable.

like image 136
Stephan Avatar answered Oct 01 '26 16:10

Stephan


I don't understand why you make it so difficult. You say

I want to implement a version where the method doSomething returns the parameter a back.

Well, you can do just that:

public class SomeImplementation<A> implements SomeInterface<A, A> {
    public A doSomething(A a) {
        // do stuff
        return a;
    }
}

No need for a Holder class. The interface SomeInterface does not put any constraints on the type parameters, so there's no reason why they can't be the same.

Alternatively, you can allow your implementation to be parameterized with two different types A and B where A extends B (could be useful in some cases):

public class SomeImplementation<A extends B, B> implements SomeInterface<A, B> {
    public B doSomething(A a) {
        // do stuff
        return a;
    }
}
like image 35
herman Avatar answered Oct 01 '26 15:10

herman