Search code examples
javaclassloaderdynamic-class-loaders

Dynamic Class loading in java


I have some weird requirment I need to load a class dynamically,

here I have an 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

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. so my propertie looks like this 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); My requirment is I want House Instance which internally holds DuplexHouse object How can I do that ??


Solution

  • First do Class.forName. This will give you the DuplexHouse class in the form of Class<?>. On that, do newInstance(). It will give you the instance of DuplexHouse in the form of an Object. Cast this to House and you have your DuplexHouse instance in the form of House.

    This assumes (1) the DuplexHouse class in in the class path (2) DuplexHouse constructor takes zero arguments.