[英]Is it useful to provide a type-safe method?
I'm designing the interface as follows: 我正在设计界面,如下所示:
public interface Parameters {
public <T> T getValue(ParameterName pn, Class<T> valueType) throws ClassCastException;
}
An implementation is obligated to throw ClassCastException
if the Class
instance of the value to be returned is not an assignableForm of the Class
passed as a parameter. 如果要返回的值的
Class
实例不是作为参数传递的Class
的AssignableForm ,则实现必须抛出ClassCastException
。
Does it make sesnse? 它会引起感冒吗? It provides compile-time type-safety, but we can do the same with just explicit cast.
它提供了编译时的类型安全性,但是我们可以通过显式强制转换来做到这一点。
Or it's much better to declare just 或者最好只声明
public Object getValue(ParameterName pn)
leaving all class-cast issues to the client. 将所有类转换问题留给客户端。
I have used this form of API where I add the ability to convert the type to the one desired. 我使用了这种形式的API,在其中添加了将类型转换为所需类型的功能。 eg if it's a String but you need an Integer it will attempt to parse it.
例如,如果它是一个字符串,但是您需要一个整数,它将尝试解析它。
Otherwise, as you suggest you are not adding much that this method doesn't provide. 否则,如您建议的那样,您不会添加该方法没有提供的内容。
public <T> T getValue(ParameterName pn);
This avoid needing an explicit cast. 这样可以避免显式强制转换。
It is a misunderstanding that you gain any compile-time type-safety by passing the Class
object of the expected return type as a parameter. 误解是通过将预期返回类型的
Class
对象作为参数传递来获得编译时的类型安全。 If the client passes a Class
of the wrong type the error will only get detected at runtime. 如果客户端传递了错误类型的
Class
,则仅在运行时才会检测到错误。
But I think the design with a Class
parameter has other advantages: 但是我认为带有
Class
参数的设计还有其他优点:
Class
parameter and provide a specific and meaningful error message if the user makes a mistake. Class
参数,并在用户犯错时提供特定且有意义的错误消息。 I can think of two disadvantages of that design: 我可以想到该设计的两个缺点:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.