简体   繁体   English

用Java动态加载类

[英]Dynamic Class loading in java

I have some weird requirment I need to load a class dynamically, 我有一些奇怪的要求,我需要动态加载类,

here I have an Interface 这里我有一个Interface

    public interface House
    {
       public Object loadHouseModel(String type);
       public Object loadHouseSpace(String type); 
     } 

now the desired class will implement this interface 现在所需的类将实现此接口

     public class DuplexHouse implements House 
     {
        public Object loadHouseModel(String type)
        {
             ///Method body goes here
        }
        public Object loadHouseSpace(String type)
         {
             ///Method body goes here
         }
      }   

Now my requirement is that I need to load DuplexHouse or whatever the class which implements House 现在我的要求是我需要加载DuplexHouse或实现House任何类

Requirment is that DuplexHouse class name I will get it from properties and All I know is The class name I get will Implement the House Interface. 要求是DuplexHouse类名,我将从属性中获得它,而我所知道的是,我获得的类名将实现House接口。 so my propertie looks like this type_house=xx.xx.xxx.DuplexHouse,xx.xx.xx.TruplexHouse,..etc 所以我的属性看起来像这样type_house=xx.xx.xxx.DuplexHouse,xx.xx.xx.TruplexHouse,..etc

Based on the type of House I need to load corresponding house object 根据房屋的类型,我需要加载相应的房屋对象

So in my main class Class cl = Class.forName(xx.xxx.xxx.DuplexHouse); 所以在我的主类中, Class cl = Class.forName(xx.xxx.xxx.DuplexHouse); My requirment is I want House Instance which internally holds DuplexHouse object How can I do that ?? 我的要求是我想要内部包含DuplexHouse对象的House实例,该怎么办?

First do Class.forName . 首先做Class.forName This will give you the DuplexHouse class in the form of Class<?> . 这将为您提供Class<?>形式的DuplexHouse类。 On that, do newInstance() . 在此上,执行newInstance() It will give you the instance of DuplexHouse in the form of an Object . 它将以Object的形式为您提供DuplexHouse的实例。 Cast this to House and you have your DuplexHouse instance in the form of House . 铸造这House ,你有你DuplexHouse实例的形式House

This assumes (1) the DuplexHouse class in in the class path (2) DuplexHouse constructor takes zero arguments. 这假设(1)类路径中的DuplexHouse类(2)DuplexHouse构造函数采用零参数。

@Babel I could not quite understand your question, but you're able to check if an object is an instance of any class or interface with the instanceof keyword. @Babel我不太理解您的问题,但是您可以使用instanceof关键字检查对象是否是任何类或接口的instanceof

For example 例如

boolean isLion = felineAnimal instanceof Lion boolean isWolf = canineAnimal instanceof Wolf

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

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