0

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 ??

8
  • 2
    What do you need to do with the Class object? Is anything preventing you from just instantiating House house = new DuplexHouse() ? Commented Feb 15, 2017 at 4:03
  • use generics for anything that implements interface use like ClassName<T extends House> Commented Feb 15, 2017 at 4:03
  • @TimBiegeleisen I can not Instantiate House with DuplexHouse cause DuplexHouse is unknow that time I take this class name from property. All I know is that DuplexHouse implements House Commented Feb 15, 2017 at 4:16
  • 1
    Try method Class.newInstance() Commented Feb 15, 2017 at 4:19
  • 1
    So why can't you just do House house = (House)Class.forName("xxx.xxx.xxx.DuplexHouse").newInstance();? Commented Feb 15, 2017 at 4:23

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

@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.

For example

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.