英文:
Runtime class casting java
问题
public static Object convertObject(Object source, Object target){
return (target.getClass())source; // IDE: 'not a statement'
}
英文:
How to convert source object to target object?
public static Object convertObject(Object source, Object target){
return (target.getClass())source; // IDE: 'not a statement'
}
答案1
得分: 2
我不完全确定你想要做什么,但要将其强制转换为运行时类型,你需要使用方法 Class.cast:
public static Object convertObject(Object source, Object target){
return target.getClass().cast(source);
}
这会实现你所要求的功能,但实际上并没有太多意义。如果类型实际上不匹配,它会在运行时抛出 java.lang.ClassCastException
。实际上,这个检查几乎是它唯一要做的事情。
英文:
I'm not completely sure what you are trying to do, but to cast to a runtime type, you need the method Class.cast:
public static Object convertObject(Object source, Object target){
return target.getClass().cast(source);
}
This does what you are asking, but it doesn't really make much sense. It does throw java.lang.ClassCastException
at runtime if the types don't actuelly match. This check is actually pretty much the only thing this does.
答案2
得分: 1
如果您确实需要进行一些转换,应该通过通用方法来完成:
public static <T> T convert(Object source, Class<T> targetClass) {
return targetClass.cast(source);
}
public static Object convertObject(Object source, Object target) {
return target.getClass().cast(source);
}
调用这个方法至少之后,就不需要显式地进行类型转换了。
static class A {
String foo() { return "A"; };
}
static class B extends A {
String foo() { return "B"; };
}
static class C extends B {
String foo() { return "C"; };
}
测试:
A c = new C();
A b1 = new B();
B b = convert(c, B.class);
B b2 = convertObject(c, b1); // 不兼容的类型:无法将 Object 转换为 B
// 需要显式转换 (B) convertObject(c, b1);
英文:
If you really need to do some conversion, this should be done via generic method:
public static <T> T convert(Object source, Class<T> targetClass) {
return targetClass.cast(source);
}
public static Object convertObject(Object source, Object target) {
return target.getClass().cast(source);
}
At least after calling this method, no explicit casting is required.
static class A {
String foo() { return "A"; };
}
static class B extends A {
String foo() { return "B"; };
}
static class C extends B {
String foo() { return "C"; };
}
test
A c = new C();
A b1 = new B();
B b = convert(c, B.class);
B b2 = convertObject(c, b1); // incompatible types: Object cannot be converted to B
// explicit casting needed (B) convertObject(c, b1);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论