简体   繁体   English

运行时类转换 java

[英]Runtime class casting java

How to convert source object to target object?如何将源对象转换为目标对象?

public static Object convertObject(Object source, Object target){
      return (target.getClass())source;    // IDE: 'not a statement'
}

I'm not completely sure what you are trying to do, but to cast to a runtime type, you need the method Class.cast :我不完全确定您要做什么,但是要转换为运行时类型,您需要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.如果类型实际上不匹配,它会在运行时抛出java.lang.ClassCastException This check is actually pretty much the only thing this does.这项检查实际上几乎是唯一要做的事情。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM