简体   繁体   中英

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 :

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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