Home > Software design >  How to design a method that can deal with two different object types
How to design a method that can deal with two different object types

Time:05-20

I have two collections, that have almost similar attributes:

HashSet<BuyerUser>
HashSet<SellerUser>

I want to write a method that serializes the objects as JSON and sends it to a web API. My problem is, however, that i'm not able to write a method that is generic enough so that I don't have to repeat the code twice.

public void addToMetadata (Object users) {

   if (users instanceof BuyerUser) {
        // Do this

    }
    if (users instanceof SellerUser) {
        // Do that

    }
}

My problem is the instanceOf check that doesn't work the way I outlined it. I would have to do something like

if (users instanceof HashSet<BuyerUser>)

but that gives me an error:

llegal generic type for instanceof

Can that be solved in any way?

CodePudding user response:

if (users instanceof HashSet<BuyerUser>)

You cannot do this, as generics are erased at runtime when the instanceof call is run

Instead, the better way to go would get to create either a parent class of BuyerUser and SellerUser or an interface that both BuyUser and SellerUser have that has a function like

public String toJSON ()

CodePudding user response:

Since the parameterized type is lost on runtime, you cannot do it. You can either create a wrapper for each HashSet and add a method to it which returns the type:

public class MySet<T> extends HashSet<T> {
     private Class<T> type;

     public MySet(Class<T> c) {
          this.type = c;
     }

     public Class<T> getType() {
          return type;
     }
}

Or you can get the first element of the set and check the type of that:

if(set instanceof HashSet && !set.isEmpty() && set.iterator().next() instanceof BuyerUser) {
    // BuyerUser set
}

Be aware the set may contain different types of objects like if it was defined as HashSet<Object>.

  •  Tags:  
  • java
  • Related