使用枚举参数自动推断返回类型 [英] Automatically infer return type using enum parameter

查看:143
本文介绍了使用枚举参数自动推断返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我希望能够支持这些调用,如果我给Enum作为Java中的方法的参数,是否可以自动推断返回类型?通过在枚举中使getValue通用和使用信息

  String myval = obj.getValue(MyEnum.Field1)
int myval2 = obj.getValue(MyEnum.Field2)

当前解决方案 p>

我目前的解决方案是这样的:



String val = typeRow.getColumnValueGen(TYPEGODKENDCRM。 COLUMN_TYPEGODKENDNR,String.class)



它用于访问表的ORM表示中的列。我知道这个字段是一个字符串,我想避免每次调用时都要告诉它。

解决方案


如果我给一个枚举作为Java中的方法的参数,自动推断返回类型?


否。您不能通过Java中的返回类型来重载方法,如果您想要的话:

  public< T> T getValue(MyEnum enumValue)

编译器无法推断出 T 基于参数。类型推断可以在一些案例中工作,但不是这样。编译器无法检查参数的某些方面,并推断甚至根据该值来验证类型。



除了别的什么,你会期待什么如果参数不是编译时常量,那么要做吗?

  MyEnum x = getEnumValue ); 
//这是否有效?
String myVal = obj.getValue(x);

基本上你会来转换返回值... int 的情况,您需要转换为整数而不是 int ,然后让自动取消装箱做其他事情。



我个人只是创建了多种方法:

  String x = obj.getString(...); 
int y = obj.getInt(...);

没有任何歧义的空间,不需要任何聪明的泛型等。


Is it possible to automatically infer the return type if I give an Enum as parameter to a method in Java?

I would like to be able to support these calls by making getValue generic and using information in the Enum

String myval = obj.getValue(MyEnum.Field1)
int myval2 = obj.getValue(MyEnum.Field2)

Current solution

My current solution does like this:

String val = typeRow.getColumnValueGen(TYPEGODKENDCRM.COLUMN_TYPEGODKENDNR, String.class)

It's for accessing columns in a ORM representation of a table. I known that this field is a string, I would like to avoid having to tell it at every call.

解决方案

Is it possible to automatically infer the return type if I give an Enum as parameter to a method in Java?

No. You can't overload methods by return type in Java, and if you wanted something like:

public <T> T getValue(MyEnum enumValue)

there's no way for the compiler to infer T based on the argument. Type inference can work in some cases, but not like this. There's no way for the compiler to examine some aspect of the argument and infer or even validate the type based on that value.

Aside from anything else, what would you expect it to do if the argument weren't a compile-time constant?

MyEnum x = getEnumValue();
// Is this valid or not?
String myVal = obj.getValue(x);

Basically you would have to cast the return value... and in the case of int, you'd need to cast to Integer rather than int, and then let auto-unboxing do the rest.

Personally I'd just create multiple methods:

String x = obj.getString(...);
int y = obj.getInt(...);

That leaves no room for ambiguity, doesn't require any cleverness with generics etc.

这篇关于使用枚举参数自动推断返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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