Java:一种具有多种返回类型的函数...是否可以使用泛型? [英] Java: One function with many return types... Is it possible with generics?

查看:242
本文介绍了Java:一种具有多种返回类型的函数...是否可以使用泛型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public String fetchValueAsString(String key)为了简单起见,我有几个过程,如下所示: ; 
public DateTime fetchValueAsDateTime(String key);

我想要类似于

  public< X是一个字符串或一个DateTime> X fetchValue(String key); //伪代码

我可以像这样调用(不需要转换;类型由传递参数):

  String str = fetchValue(subject); 
DateTime dt = fetchValue(startDate);

我知道我可以有一个方法返回Object类型,只是进行转换,但我想知道是否有一种方法我可以只调用一个方法,并以某种方式使用泛型来确定返回值。那么,是否可以在Java中使用(它是用C# a>)?

当然,只有在传入参数隐含数据类型时才能使用。



我可以声明以下内容并且不会出现错误:

  public static< T> ; T parseString(String s){
return(T)new Date();
}

public static void test(){
Date dt = parseString(date);
}

但是这种事情的结果是解析函数的内部是必须能够查看字符串并确定目标类型,并且必须在其内部进行大量投射才能正常工作。



您的问题会在某种程度上含糊不清,或者你真正想要的是让接收器的类型决定调用的方法还是方法内部的行为。这是AFAIK不可能的。一旦你在方法中,所有你需要处理的是字符串。


I have a few procedures that, for simplicity's sake, look like the following:

public String fetchValueAsString(String key);
public DateTime fetchValueAsDateTime(String key);

I want something like

public <X is a String or a DateTime> X fetchValue(String key);  // pseudo-code

that I could call like this (without casting; the type is implied by the passed parameters):

String str = fetchValue("subject");
DateTime dt = fetchValue("startDate");

I know I could just have one method that returns the Object type and just do a casting conversion, but I'm wondering if there is a way I can have just one method called, and somehow use generics to determine the return value. So, is it possible in Java (it is in C#)?

解决方案

Sure, but it will only work if the datatype is implied by the passed parameter.

I can declare the following and get no error:

public static <T> T parseString(String s) {
    return (T) new Date();
}

public static void test() {
    Date dt = parseString("date");
}

But the upshot to this kind of thing is the interior of your parsing function is going to have to be able to look at the string and determine the target type and its going to have to do a lot of casting inside its body to work properly.

Your question leaves somewhat ambiguous whether this is the kind of thing you want, or if what you really want is to have the type of the receiver determine either the method called or the behavior inside the method. This is, AFAIK not possible. Once you're in the method, all you have to work with is the string.

这篇关于Java:一种具有多种返回类型的函数...是否可以使用泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆