简体   繁体   English

在运行时加载的类的对象转换

[英]Casting of object for a class loaded at runtime

i load a class using 我使用加载课程

Class.forName(klassname,false,loader) Class.forName(类别名称,false,加载程序)

After this i create an instance using 之后,我使用创建实例

klass.newInstance(); klass.newInstance(); It returns an object type.I want to cast it to specific type(ie.Klassnamw instance).I used normal casting but it gets hung because it is not resolved during runtime.How can i cast it?Hellp 它返回一个对象类型。我想将其强制转换为特定类型(例如,Klassnamw实例)。我使用普通的强制转换,但由于在运行时无法解析而被挂起,我该如何对其进行强制转换?

Casting is usually used to give the compiler more information. 通常使用强制转换为编译器提供更多信息。 You don't have that information at compile-time, so you can't give it to the compiler. 您在编译时没有该信息,因此无法将其提供给编译器。

Moreover, the point of casting is usually so that you can get to some member of the class which wouldn't be known otherwise - but if you don't know the class until execution time, how can you know the members? 此外,强制转换的目的通常是使您可以到达该类的某个其他成员,而这些成员本来不会被其他人知道-但是,如果您直到执行时才知道该类,那么如何知道这些成员呢?

There are certain cases where it would be nice, but they're pretty uncommon. 在某些情况下会很好,但很少见。 What are you trying to do with the instance after you've created it? 创建实例后,您打算如何处理它? If you're trying to call methods which you do know about at compile time, can you make those methods part of an interface and cast to the interface ? 如果您尝试在编译时调用您确实知道的方法,那么可以将这些方法作为接口的一部分并转换为接口吗?

You are using reflection because you do not know (or cannot resolve) the class to be loaded at compile time. 您之所以使用反射,是因为您不知道(或无法解析)在编译时要加载的类。

As such, you cannot cast to the class. 因此,您不能上课。

Unless there is an interface (or parent class) that you can resolve at compile-time (and thus cast to), you have to use reflection to do anything useful with the object. 除非有一个可以在编译时解析(然后转换为它)的接口(或父类),否则您必须使用反射对对象执行任何有用的操作。

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

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