开发者

How is it possible to cast an interface to a class?

开发者 https://www.devze.com 2023-02-22 18:47 出处:网络
I have an interface Class object provided as a method parameter, and I also have a Object instance of the object being casted.

I have an interface Class object provided as a method parameter, and I also have a Object instance of the object being casted.

Task: To cast the object as if I would do the interface = object thing but manually using Class.cast() method.

And the star of the show:

def readObject(type, path) {
        Object obj
        // Prevent playing with NPE
        if (groovyClassLoader == null)
            groovyClassLoader = new GroovyClassLoader(getClass().getClassLoader())

        // The final quest begins
        try {
            Class groovyClass = groovyClassLoader.parseClass(new File(path))

// at this point: type ins an instance of Class which is an interface
// to which I need to assign the obj instance

// groovyClass is an instance of Class 
开发者_JAVA技巧// out of which I need to get object and eventually cast it to type
// so something like:
//            groovyClass = groovyClass.cast(type)
//            obj = groovyClass.newInstance()
// or
//            obj = groovyClass.newInstance()
//            obj = groovyClass.cast(type)



            obj = groovyClass.newInstance()
            obj = type.cast(obj)

        } catch (ex){
            //TODO:IO and obj creation exception should be logged
            ex.printStackTrace()
        }
        return obj
    }

This is a mighty warior quest for survival with mage casting and I'm starting to feal that my mission is out of mighty land possibilities XD


You cannot create an instance of an interface. You must first define a class that implements the interface and then create an instance of that class. You can then pass this object as an argument to any method that accepts a parameter of the interface type.


You cannot have an instance to an interface. Interface is just like a template. The concrete classes that implement the interface can have their own instances. Suppose I have the following:

public interface IExample {
  public void foo();
}

class Example implements IExample {
  public void foo() {
    // do something
  }
}

class MyMain {
  public static void main(String[] args) {
    IExample iExample;
    Example example = new Example();

    iExample = example; // Polymorphism :)

    // IExample iExample = new IExample();  -- is wrong
  }
}

In the above example, the object "example" can be casted to IExample (Polymorphism) but you cannot have memory allotted for the IExample interface since it does nothing.

0

精彩评论

暂无评论...
验证码 换一张
取 消