Runtime class casting java

huangapple go评论60阅读模式
英文:

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 &lt;T&gt; T convert(Object source, Class&lt;T&gt; 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 &quot;A&quot;; };
}

static class B extends A {
    String foo() { return &quot;B&quot;; };
}

static class C extends B {
    String foo() { return &quot;C&quot;; };
}

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

huangapple
  • 本文由 发表于 2020年10月11日 03:39:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/64297523.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定