如何仅通过拥有 class 对象来实例化 class 并仅通过使用实例化它的 class 来转换结果?
How to instantiate a class just by having the class object and cast the result just by using the class from which it was instantiated?
我遇到以下问题:
我有一个 class 对象(MyClass.class),从那个 class 对象我需要实例化一个 object.That 是简单的部分 ois MyClass.class.getDeclaredConstructor().newInstance()
(class 只有一个不带参数的构造函数)。
棘手的部分(或者我认为)是使用我创建的 class 对象将结果对象转换为适当的类型 (MyClass)。
注意我不能写下面的代码(MyClass)MyClass.class.getDeclaredConstructor().newInstance()
如果有人能帮助我,我将不胜感激。
写入:
MyClass.class.cast(myInstance);
See also the relevant Javadoc。并不是说除了空值检查和类型检查之外这将非常有用:
public T cast(Object obj) {
if (obj != null && !isInstance(obj))
throw new ClassCastException(cannotCastMsg(obj));
return (T) obj;
}
...但这就是你如何使用反射来转换 class,我怀疑这个问题无论如何都是关于一些测试或作业的
我遇到以下问题:
我有一个 class 对象(MyClass.class),从那个 class 对象我需要实例化一个 object.That 是简单的部分 ois MyClass.class.getDeclaredConstructor().newInstance()
(class 只有一个不带参数的构造函数)。
棘手的部分(或者我认为)是使用我创建的 class 对象将结果对象转换为适当的类型 (MyClass)。
注意我不能写下面的代码(MyClass)MyClass.class.getDeclaredConstructor().newInstance()
如果有人能帮助我,我将不胜感激。
写入:
MyClass.class.cast(myInstance);
See also the relevant Javadoc。并不是说除了空值检查和类型检查之外这将非常有用:
public T cast(Object obj) {
if (obj != null && !isInstance(obj))
throw new ClassCastException(cannotCastMsg(obj));
return (T) obj;
}
...但这就是你如何使用反射来转换 class,我怀疑这个问题无论如何都是关于一些测试或作业的