我想在我的api中提供类似的东西:
class Foobar extends AbstractThing<Double>
class EventThing<Foobar> {
public Foobar getSource();
public Double getValue();
}
Run Code Online (Sandbox Code Playgroud)
所以我写这个:
class EventThing<T extends AbstractThing<U>> {
public T getSource();
public U getValue();
}
Run Code Online (Sandbox Code Playgroud)
但java无法解决U.
随着EventThing<T extends AbstractThing<U>,U>代替它的工作原理,但第二个U实际上是多余的"导致AbtractThing已定义的类型.所以我喜欢摆脱它.
我正在尝试创建一个Handler接口,它能够根据事件的类型处理不同类型的事件。我遇到以下警告问题:
Unchecked call to 'handle(T)' as a member of raw type 'Handler'
这是我的课程。
public interface Handler<T> {
void handle(T event); }
public class IntegerHandler implements Handler<Integer> {
@Override
public void handle(Integer event) {
System.out.println("Integer: " + event);
}
}
public class ObjectHandler implements Handler<Object> {
@Override
public void handle(Object event) {
System.out.println("Object: " + event);
}
}
public class StringHandler implements Handler<String> {
@Override
public void handle(String event) {
System.out.println("String: " + event);
}
}
public class TestHandlers …Run Code Online (Sandbox Code Playgroud) 如何使用Java8 Supplier接口重写此工厂方法以提供正确的类型化实例?
我有一个扩展Map的简单界面:
public interface Thingy<K, V> extends Map<K, V> {}
Run Code Online (Sandbox Code Playgroud)
然后我有一个ThingyFactory类,其中包含Thingy所有实现类名的列表:
public final class ThingyFactory {
Map<String, Class<Thingy<?, ?>>> thingyclasses = new ConcurrentHashMap<>();
.....
@SuppressWarnings("unchecked")
public <K, V> Thingy<K, V> getInstance(String classname) throws ThingyException {
Thingy<K, V> thingy;
try {
thingy = (Thingy<K, V>) thingyclasses.get(classname).newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new ThingyException("Something bad happened: ", e.toString());
}
return thingy;
}
}
Run Code Online (Sandbox Code Playgroud)
我很确定我能够优雅地完成这项任务,并且没有使用供应商界面的SuppressWarnings和类加载器,但我似乎无法使模式非常正确.任何指导赞赏!
在Java中是否可以创建一个静态工厂方法/类,它使用接口作为参数化类型并返回给定接口的实现类?
虽然我对泛型的了解有限,但这就是我想要做的:
// define a base interface:
public interface Tool {
// nothing here, just the interface.
}
// define a parser tool:
public interface Parser extends Tool {
public ParseObject parse(InputStream is);
}
// define a converter tool:
public interface Converter extends Tool {
public ConvertObject convert(InputStream is, OutputStream os);
}
// define a factory class
public class ToolFactory {
public static <? extends Tool> getInstance(<? extends Tool> tool) {
// what I want this method to return is: …Run Code Online (Sandbox Code Playgroud)