[英]Java Generic Conversion from Legacy Code to Generic
如何将遗留枚举转换为“通用”枚举? 我想确保枚举中每个元素的类型都是正确的。 我想确保在代码中没有进一步的运行时转换错误,特别是当我没有捕获它们时。
这是我的示例代码。
import java.util.Enumeration;
import java.util.Vector;
public class TestEnumerationCast {
public static void main(String[] args) {
new TestEnumerationCast();
}
{
Vector stringVector = new Vector();
stringVector.add("A");
stringVector.add("B");
stringVector.add("C");
stringVector.add(new Integer(1));
Enumeration<String> enumerationString = castEnumeration(stringVector.elements());
while (enumerationString.hasMoreElements()) {
String stringToPrint = enumerationString.nextElement();
System.out.println(stringToPrint);
}
}
private <T> Enumeration<T> castEnumeration(Enumeration<?> elements) {
Vector<T> converstionVector = new Vector<T>();
while (elements.hasMoreElements()) {
try {
converstionVector.add((T) elements.nextElement());
} catch (Exception e) {
}
}
return converstionVector.elements();
}
}
我认为方法castEnumeration会将遗留代码“转换”为任何类型的通用代码。 简单地说,我遍历每个元素,试图将其转换为(T)。 如果失败,我抛出一个运行时异常,但只跳过该元素。 然后我有一个只有类型的枚举。 但是,将类型添加到向量的行不会捕获整数。 我仍然在最后一个元素(整数)的字符串转换中获得运行时异常。
我知道我可以直接转换为泛型类型,忽略错误等等。所有这些都是有效的方法。 但我想确保在我不寻找它时不会得到运行时异常。 谢谢
啊,发现了! 您必须在转换中将要使用的类指定为方法参数,然后使用.cast(obj)方法。
更改来电
private <T> Enumeration<T> castEnumeration(Enumeration<?> elements) {
Vector<T> converstionVector = new Vector<T>();
while (elements.hasMoreElements()) {
try {
converstionVector.add((T) elements.nextElement());
} catch (Exception e) {
}
}
return converstionVector.elements();
}
至
private <T> Enumeration<T> castEnumeration(Enumeration<?> elements, Class<T> tClass) {
Vector<T> converstionVector = new Vector<T>();
while (elements.hasMoreElements()) {
try {
converstionVector.add(tClass.cast(elements.nextElement()));
} catch (Exception e) {
}
}
return converstionVector.elements();
}
并且还要更改方法的调用
Enumeration<String> enumerationString = castEnumeration(stringVector.elements());
至
Enumeration<String> enumerationString = castEnumeration(stringVector.elements(), String.class);
总的来说,代码现在看起来像。
import java.util.Enumeration;
import java.util.Vector;
public class TestEnumerationCast {
public static void main(String[] args) {
new TestEnumerationCast();
}
{
Vector stringVector = new Vector();
stringVector.add("A");
stringVector.add("B");
stringVector.add("C");
stringVector.add(new Integer(1));
Enumeration<String> enumerationString2 = castEnumeration(stringVector.elements(), String.class);
while (enumerationString2.hasMoreElements()) {
String stringToPrint = enumerationString2.nextElement();
System.out.println(stringToPrint);
}
}
private <T> Enumeration<T> castEnumeration(Enumeration<?> elements, Class<T> tClass) {
Vector<T> converstionVector = new Vector<T>();
while (elements.hasMoreElements()) {
try {
converstionVector.add(tClass.cast(elements.nextElement()));
} catch (Exception e) {
}
}
return converstionVector.elements();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.