英文:
Java generic type conversion like <String, String> to <Object, Object>
问题
从:<Object, Object>
到:<String, String>
或者
从:<String, String>
到:<Object, Object>
我在 ConcurrentKafkaListenerContainerFactory<Object, Object>
和 ConcurrentKafkaListenerContainerFactory<String, String>
之间有这种情况。
英文:
Is there a way in java to convert type
from : <Object, Object>
to : <String, String>
or
from : <String, String>
to : <Object, Object>
I have it between ConcurrentKafkaListenerContainerFactory<Object, Object>
and ConcurrentKafkaListenerContainerFactory<String, String>
答案1
得分: 2
以下是翻译好的部分:
你必须使用中间的原始类型。这里有一个从 Object
到 String
转换的示例。反向转换看起来是相同的。
static ConcurrentKafkaListenerContainerFactory<Object, Object> stringFactoryToObjectFactory(
ConcurrentKafkaListenerContainerFactory<String, String> stringFactory) {
@SuppressWarnings("rawtypes")
ConcurrentKafkaListenerContainerFactory rawTypeFactory = stringFactory;
@SuppressWarnings("unchecked")
ConcurrentKafkaListenerContainerFactory<Object, Object> objectFactory = rawTypeFactory;
return objectFactory;
}
当然,这违反了类型安全性,如果这些工厂使用不同的类型,将在运行时引发 ClassCastException
。
英文:
You have to use intermediate raw type. Here's an example for Object
to String
conversion. Reverse conversion will look identical.
static ConcurrentKafkaListenerContainerFactory<Object, Object> stringFactoryToObjectFactory(
ConcurrentKafkaListenerContainerFactory<String, String> stringFactory) {
@SuppressWarnings("rawtypes")
ConcurrentKafkaListenerContainerFactory rawTypeFactory = stringFactory;
@SuppressWarnings("unchecked")
ConcurrentKafkaListenerContainerFactory<Object, Object> objectFactory = rawTypeFactory;
return objectFactory;
}
Of course it violates type safety and ClassCastException
will occur at runtime, if those factories will use different types.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论