我有两个警告:
unchecked cast, required: A found: capture#1 of ?unchecked cast, required: A found: Congress我知道这门课实际上是一项活动。
其中事件是一个接口,展览和大会都实现了事件接口。
public static <A extends Event> A copy(A event) {
Class<?> eventType = event.getClass(); // --> Warning 1
return (A) eventType.getConstructor(eventType).newInstance(event);
return event;
}第二个警告:
public static <A extends Event> A create(EventType type) {
if(type == EventType.CONGRESS){
return (A) new Congress() // --> Warning 2
}else(){
return (A) new Exhibition() // --> Same as warning 2 but for Exibition
}
}现在的问题是:如何解决这两个警告而不使用:
@SuppressWarning("unchecked")发布于 2018-06-17 11:27:28
看来你在滥用仿制药。如果该方法决定返回的类型,则不应使用泛型。当调用方决定返回哪种类型时,使用泛型。
所以create应该是这样的:
public static Event create(EventType type) {
if(type == EventType.CONGRESS){
return new Congress();
}else {
return new Exhibition();
}
}对于第一个警告,您可以这样做。
public static <A extends Event> A copy(A event) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
return (A) event.getClass().getConstructor(event.getClass()).newInstance(event);
}发布于 2018-06-17 11:42:12
你为什么要让这成为一个静态的方法?
public static <A extends Event> A copy(A event) {
Class<?> eventType = event.getClass(); // --> Warning 1
return (A) eventType.getConstructor(eventType).newInstance(event);
return event;
}您有一个事件实例,让Event类能够创建自己的副本。
abstract class Event<E extends Event<E>> {
public E createCopy(E toCopy);
}使用
class Exhibition extends Event<Exhibition> {
// ...
public Exhibition createCopy() {
return new Exhibition(this);
}
}要消除第二个警告,您可以将EventType调整为
public enum EventType {
CONGRESS { public Event createEvent() { return new Congress(); }},
EXHIBITION { public Event createEvent() { return new Exhibition(); }};
public abstract Event createEvent();
}这将导致
public static Event create(EventType type) {
return type.createEvent();
}如果确实有必要知道返回的事件的确切类型,那么就应该重新考虑设计。
发布于 2018-06-17 12:01:59
我建议使用TypeTags,aka,ClassTags。类似于:
public static <A extends Event> Optional<A> create(Class<A> classTag) {
try {
return Optional.of(classTag.newInstance());
} catch (InstantiationException | IllegalAccessException e) {
return Optional.empty();
}
}就这么说吧:
public static void main(String[] args) {
Optional<Exhibition> e = create(Exhibition.class);
e.ifPresent(System.out::println);
}https://stackoverflow.com/questions/50896042
复制相似问题