简体   繁体   English

如何使用泛型将这两种方法合而为一?

[英]How to use generics to combine these two methods Into one?

I know a lot of Java Generics questions like this already exist such as ( How to refactor two Java methods into one? ), but I guess I just need to see it with my own, simpler function -- with an example of how to call it, to completely understand java generics...I apologize and thank you in advance! 我知道很多这样的Java泛型问题已经存在,例如( 如何将两个Java方法重构为一个? ),但是我想我只需要用自己的更简单的函数来查看它-并举例说明如何调用为了完全理解Java泛型...在此致歉,并先谢谢您!

All I know Is that I will probably need to use instanceof, and Class.forName to handle the different return types (and possibly add a second argument for the desiredClass, or can this be deduced somehow without adding the second argument?) 我所知道的是,我可能需要使用instanceof和Class.forName来处理不同的返回类型(并可能为期望的类添加第二个参数,或者可以在不添加第二个参数的情况下以某种方式推论得出?)

public static <T> T getSanitizedURI(String theUrl, Class desiredReturnType) {
}

but then what? 但是那又怎样呢?

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;
    }

In my opinion, this is not a good use case for generics. 我认为,这不是泛型的好用例。 If the user wants a String they can use the method that returns a String . 如果用户需要String则可以使用返回String的方法。 If they want a URI they can use the method that returns a URI . 如果他们想要URI则可以使用返回URI的方法。 Generics would be more appropriate if it is not possible to determine at the time of writing the method all the different types that the method could be used for, or if the method is to be used for lots of different types. 如果无法在编写方法时确定该方法可以使用的所有不同类型,或者如果该方法用于许多不同类型,则泛型将更为合适。

However, you can reduce the code duplication as follows 但是,您可以减少代码重复,如下所示

public static String getSanitizedURIString(String theUrl) {
    return getSanitizedURI(theUrl).toASCIIString();
}

Note that this will throw a NullPointerException if getSanitizedURI returns null . 请注意,如果getSanitizedURI返回null ,则将抛出NullPointerException You may prefer to handle this case differently, such as returning theUrl as suggested by @ViacheslavVedenin. 您可能希望以不同的方式处理这种情况,例如按theUrl建议返回TheUrl。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM