0

Can someone please guide me on this. I have a class loader which I could load a class using Java reflection. However, is there anyway I can cast my object to an interface? I understand that there is a ServiceLoader but I read it is highly not recommended.

//returns a class which implements IBorrowable
public static IBorrowable getBorrowable1()  
{
    IBorrowable a;  //an interface
     try
        {
            ClassLoader myClassLoader = ClassLoader.getSystemClassLoader();
            a = (IBorrowable) myClassLoader.loadClass("entityclasses.Books");

        }
    catch (Exception e ){
        System.out.println("error");
    }
    return null;
}
3
  • You need to invoke newInstance() on the returned class before casting it. This of course assumes you have a default constructor on the actual class. Commented Mar 19, 2013 at 9:53
  • @StephenC - his exception handling is indeed horrible, but thats not the problem with his current code. Commented Mar 19, 2013 at 10:04
  • I just realised. I'm too tired. Commented Mar 19, 2013 at 10:18

2 Answers 2

1

Looks like you are missing an object instantiation.

myClassLoader.loadClass("entityclasses.Books") does not return an instance of IBorrowable, but an instance of Class object, that refers to Books. You need to create an instance of the loaded class using newInstance() method

Here is fixed version (assuming, Books has default constructor)

public static IBorrowable getBorrowable1()  //returns a class which implements IBorrowable
{
     try {
        ClassLoader myClassLoader = ClassLoader.getSystemClassLoader();
        Class<IBorrowable> clazz = (IBorrowable) myClassLoader.loadClass("entityclasses.Books");
        return clazz.newInstance();
    } catch (Exception e) {
        System.out.println("error");
    }
    return null;
}
Sign up to request clarification or add additional context in comments.

Comments

1

The only thing I can see that you might be doing wrong here is using the system classloader. The chances are it won't be able to see your implementation class.

public static IBorrowable getBorrowable1()  //returns a class which implements IBorrowable
{
    IBorrowable a;  //an interface
     try
        {
            a = (IBorrowable) Class.forName("entityclasses.Books");
        }
    catch (Exception e ){
        System.out.println("error");
    }
    return a;
}

As an aside ServiceLoader for me is highly recommended.

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.