1

I have a method A

@Deprecated
public void doSomething (EnumSet <TypeA> param){

}

Now, I want to write a new method B such that it has a same signature but takes an EnumSet of different type.

public void doSomething(EnumSet <TypeB> param){

}

When I do that, eclipse gives me an error of same erasure. Is there a way to solve this purpose ? Thanks in advance. Let me know if you need more clarification.

user2453055
  • 975
  • 1
  • 9
  • 19

2 Answers2

2

Since Java compiler has type erasure, the runtime type information is unknown.

What actually happens is that both methods are compiled to

public void doSomething(EnumSet<Object> param)

hence you have two methods with the same signature, this is obviously incorrect since the JDK couldn't decide which one to invoke. You could just name them differently or use a different upper bound.

According to type erasure behavior:

Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.

Jack
  • 131,802
  • 30
  • 241
  • 343
1

When you call the method with an EnumSet<SomeType> the identity of SomeType undergoes erasure and is not known. You need to accept an instance of SomeType or Class<SomeType> to avoid erasure:

private void doSomethingA(EnumSet<TypeA>){ ... }

private void doSomethingA(EnumSet<TypeA>){ ... }

private void <T extends Enum<T>> doSomething(EnumSet<T extends BaseType> s, T tInst){
    if(t instanceof TypeA) doSomethingA(s);
    if(t instanceof TypeB) doSomethingB(s);
}

For readability, I use T and t but it could be written as:

private void <SOMETYPE extends Enum<SOMETYPE>> doSomething(EnumSet<SOMETYPE> s, SOMETYPE instanceOfSomeType){
    if(instanceOfThatType instanceof TypeA) doSomethingA(s);
    if(instanceOfThatType instanceof TypeB) doSomethingB(s);
}

Note that SOMETYPE and T are written as-is. They are placeholders at runtime, but literal at the time of writing the code.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
  • Can you elaborate on what exactly you mean by "T" and "t" – user2453055 Oct 22 '13 at 21:01
  • @user2453055 `T` is a generic type declared to extend `Enum`(i.e. it is an an enum type). `t` is just the name of a variable. I could write this as `private void > doSomething(.... SOMETYPE instanceOfThatType){`. – nanofarad Oct 22 '13 at 21:14
  • Got it. Thanks so much. *Upvote: But requires 15 reputation* :( – user2453055 Oct 22 '13 at 21:25