我最近看到可以声明一个也受接口限制的返回类型.考虑以下类和接口:
public class Foo {
public String getFoo() { ... }
}
public interface Bar {
public void setBar(String bar);
}
Run Code Online (Sandbox Code Playgroud)
我可以声明一个这样的返回类型:
public class FooBar {
public static <T extends Foo & Bar> T getFooBar() {
//some implementation that returns a Foo object,
//which is forced to implement Bar
}
}
Run Code Online (Sandbox Code Playgroud)
如果我调用该方法从什么地方,我的IDE告诉我,在返回类型的方法String getFoo(),以及setBar(String),但只有当我点了后面的点功能如下:
FooBar.getFooBar(). // here the IDE is showing the available methods.
Run Code Online (Sandbox Code Playgroud)
有没有办法获得对这样一个对象的引用?我的意思是,如果我做这样的事情:
//bar only has the method setBar(String)
Bar bar = FooBar.getFooBar(); …Run Code Online (Sandbox Code Playgroud) 使用T参数通用的方法肯定是很方便的.但是,我很好奇如果你将一个参数传递给方法,泛型方法的用途是什么Class<T> clazz.我想出了一个可能有用的案例.也许您只想根据类的类型运行方法的一部分.例如:
/** load(File, Collection<T>, Class<T>)
* Creates an object T from an xml. It also prints the contents of the collection if T is a House object.
* @return T
* Throws Exception
*/
private static <T> T void load(File xml, Collection<T> t, Class<T> clazz) throws Exception{
T type = (T) Jaxb.unmarshalFile(xml.getAbsolutePath(), clazz); // This method accepts a class argument. Is there an alternative to passing the class here without "clazz"? How can I put …Run Code Online (Sandbox Code Playgroud)