0
package test;
public interface Virtual {
    String get();
}


package test;
public class Test implements Virtual {

    static { System.out.println("hello"); }
    public Test() { System.out.println("world"); }

    @Override
    public String get() {
        return "Test clazz";
    }
}

//main method
...
Class<?> cls = Class.forName("test.Test", true, classLoader); // it prints "hello"
Virtual instance = (Virtual) cls.newInstance(); 
// this gets ClassCastException: test.Test cannot be cast to test.Virtual

The idea is get Virtual instance which is Test implementation. What is wrong with this scenario?

update: Finally I got it. It seems there was an eror in test.get().

  • If you remove your cast in `Virtual instance = (Virtual) cls.newInstance();` to be just `Virtual instance = cls.newInstance();` do you still get error? – Captain Man May 15 '15 at 21:12
  • This could help http://stackoverflow.com/questions/12383376/classcastexception-when-casting-class-forname-object-to-interface-implemented-by – Andrii Liubimov May 15 '15 at 21:15
  • @CaptainMan in this case it will not compile because of `Type mismatch: cannot convert from capture#2-of ? to Virtual`. But I can get just Object instance. –  May 15 '15 at 21:16
  • Basically it could happen when Test is loaded by another class loader then Virtual. Try pass `Virtual.class.getClassLoader()` as classloader – Andrii Liubimov May 15 '15 at 21:17
  • @AndriiLiubimov test.Test was compiled from a source file and in this case I get `ClassNotFoundException: test.Test` –  May 15 '15 at 21:34
  • Virtual instance = (Virtual) (cls.newInstance()); // cls is of Class> and cannot be casted to Virtual. – Phyrum Tea May 15 '15 at 21:43
  • @PhyrumTea If you wanted to cast `cls` you'd do `((Virtual) cls).newInstance()`. – Bubletan May 15 '15 at 21:45
  • @Bubletan I wasn't sure if method call has higher precedence level than casting. – Phyrum Tea May 15 '15 at 21:54

1 Answers1

0

Try removing cast (Virtual) Type and replace it with Test:

Virtual instance = (Virtual) cls.newInstance(); 

Change this to:

Virtual instance = Test.class.cast(cls.newInstance()); 

You cannot create an instance of Virtual as it is interface. However you can assign an instance of Test class to a reference variable which is of Virtual Type.

hitz
  • 1,100
  • 8
  • 12
  • It can not be done because of `Test cannot be resolved to a type` because it was compiled from a source file. –  May 15 '15 at 21:29
  • I have updated my answer. If it does not work can you please post more details in your original question. e.g original question does not say source file is not present. – hitz May 15 '15 at 21:38