문제

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.

도움이 되었습니까?

해결책 2

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top