简体   繁体   English

如何将对象强制转换为getClass()返回的类

[英]How to cast an object to the class returned by getClass()

ProtostuffIOUtil.mergeFrom(data,o,RuntimeSchema.getSchema(o.getClass()));

How to cast Object to getClass() Class. 如何将Object转换为getClass()类。 With the above method call, I will get a compile error because the method requires that the o variable is of the same class as the o.getClass() parameter. 使用上面的方法调用,我将得到一个编译错误,因为该方法要求o变量与o.getClass()参数属于同一个类。 How does one get around this? 怎么绕过这个?

Class clazz = o.getClass();
ProtostuffIOUtil.mergeFrom(data, clazz.cast(o), RuntimeSchema.getSchema(clazz));

使用cast()方法从getClass()将对象强制转换为类:

myObj.getClass().cast(myObj)

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

相关问题 如何将someobject.getClass()转换为Class <Object> 没有SuppressWarnings(“未选中”)? - How to cast someobject.getClass() to Class<Object> without SuppressWarnings(“unchecked”)? getClass() 方法返回的 class object 是 class 的实例吗? - Is the class object returned by getClass() method an instance of the class? Object超类中的getClass方法如何知道每个类的名称? - How does getClass method in Object superclass know the name of every Class? 如何获取父基类对象super.getClass() - How to get the parent base class object super.getClass() 如何从列表中获取typeArguments <T> 由object.getClass()。getDeclaredField(“ fieldname”)。getGenericType()返回; - How do I get typeArguments from a List<T> returned by object.getClass().getDeclaredField(“fieldname”).getGenericType(); Java Object.class和x.getClass - Java Object.class and x.getClass 强制转换由通用实例类型的 getClass() 返回的类在 Java 中总是安全的吗? - Is casting the class returned by getClass() of a generic instance type always safe in Java? 如何获得超类的this.getClass()。getConstructor? - How to get this.getClass().getConstructor of a super class? 我如何模拟Object.getClass? - How do I mock Object.getClass? 如何将 getClass() 与在 java 中具有泛型的 class 一起使用? - How to use getClass() with a class that has a generic in java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM