gpt4 book ai didi

java - Java中没有泛型参数的泛型方法

转载 作者:IT老高 更新时间:2023-10-28 20:53:24 25 4
gpt4 key购买 nike

在 C# 中我实际上可以这样做:

//This is C#
static T SomeMethod<T>() where T:new()
{
Console.WriteLine("Typeof T: "+typeof(T));
return new T();
}

//And call the method here
SomeMethod<SomeClassName>();

但由于某种原因,我无法让它在 Java 中工作。

我想做的是,在父类(super class)上创建一个静态方法,以便子类可以转换为 XML。

//This is Java, but doesn't work
public static T fromXml<T>(String xml) {
try {
JAXBContext context = JAXBContext.newInstance(T.class);
Unmarshaller um = context.createUnmarshaller();
return (T)um.unmarshal(new StringReader(xml));
} catch (JAXBException je) {
throw new RuntimeException("Error interpreting XML response", je);
}
}

//Also the call doesn't work...
fromXml<SomeSubObject>("<xml/>");

最佳答案

public static <T> T fromXml(Class<T> clazz, String xml) {

称为:

Thing thing = fromXml(Thing.class, xml);

或更明确地说:

Thing thing = MyClass.<Thing>fromXml(Thing.class, xml);

更令人困惑的是,您可以拥有既构造泛型类型又具有自身泛型参数的构造函数。不记得语法并且从未见过它在愤怒中使用(无论如何,您最好使用静态创建方法)。

强制转换(T)是不安全的,你不能写T.class。因此,将 T.class 作为参数包含在内(如 JAXBContext.newInstance 所做的那样)并在类型错误时引发相关异常。

public static <T> T fromXml(Class<T> clazz, String xml) {
try {
JAXBContext context = JAXBContext.newInstance(clazz);
Unmarshaller um = context.createUnmarshaller();
Object obj = um.unmarshal(new StringReader(xml));
try {
return clazz.cast(obj);
} catch (ClassCastException exc) {
throw new RelevantException(
"Expected class "+clazz+
" but was "+obj.getClass()
);
}
} catch (JAXBException exc) {
throw new RelevantException(
"Error unmarshalling XML response",
exc
);
}
}

我相信 JAXB 的下一个版本(在 6u14 中?)在 JAXB 类中为此类事情提供了一些方便的方法。

关于java - Java中没有泛型参数的泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/590405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com