0
我知道很多像这样的Java泛型问题已经存在,例如(How to refactor two Java methods into one?),但我想我只需要用我自己的,更简单的函数来查看它 - 以一个如何调用它的示例来完全理解java泛型...我很抱歉,并提前感谢您!如何使用泛型将这两种方法合并为一个?
我所知道的是我可能需要使用instanceof和Class.forName来处理不同的返回类型(并且可能为desiredClass添加第二个参数,或者可以在不添加第二个参数的情况下推导出它? )
public static <T> T getSanitizedURI(String theUrl, Class desiredReturnType) {
}
但那又如何?
public static URI getSanitizedURI(String theUrl) {
URI sanitizedUri = null;
try{
URL url = new URL(theUrl);
sanitizedUri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
} catch(Exception e) {
e.printStackTrace();
}
return sanitizedUri;
}
public static String getSanitizedURIString(String theUrl) {
String sanitizedUrl = theUrl;
try{
URL url = new URL(theUrl);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
sanitizedUrl = uri.toASCIIString();
} catch(Exception e) {
e.printStackTrace();
}
return sanitizedUrl;
}
请不要忘记,getSanitizedURI(theUrl)可以返回null,所以最好使用URL url = getSanitizedURI(theUrl);返回url!= null? url.toASCIIString():theUrl; –
谢谢你的回应,实际上我同意。但是,为了让我的大脑了解泛型,这怎么可能呢?我附加了另外两种方法,这可能是泛型的更好用例。 – NewJava
@ViacheslavVedenin谢谢。我编辑了答案。 –