jeudi 19 avril 2018

Code design with Java Generics

Consider the following code:

interface A<T> {
  boolean someMethod(T obj);
}

class B<T> {
   T obj;
}

class C<T> {
  B<T>[] bObjs;

  public someMethod(A<T> aParam) { 
    //do some stuff
    if(bObjs!=null && aParam!=null) {  
       for(B<T> bObj: bObjs) {
         if(aParam.someMethod(bObj.obj) {
           //doSmth
         }
       }  
      //do smth
    }
    //do smth
  }

Problem: use of bObjs and aParam is optional, but it force users of class C to use the type parameter, even when not needed. Is there a way of designing the problem so that this is unnecessary? If I use a wildcard generic such as B<?>[] bObjs and A<?> aParamthen I can't use the method aParam.someMethod(bObj.obj). Is there any way of type checking/type casting to allow use of this method without requiring type parameters? The actual code is obviously more complex, and involves a lot of logic where aParam is used if present - the use of bObjs is pretty much limited to use of a single method involving aParam.

Thanks a lot!

Aucun commentaire:

Enregistrer un commentaire