Home > Blockchain >  Implementing a method that returns a Class
Implementing a method that returns a Class

Time:05-16

There is an interface with a method that returns a Class, like so.

public interface MyInterface {
    
    public Class<? extends Object> returnsSomething ();
}

I have to create a class which implements the interface, like so.

public class MyClass implements MyInterface {
    
    public Class<? extends Object> returnsSomething () {
        
        return Object; // This is currently an error.
    }
}

The return line in the implementation of returnsSomething in MyClass is incorrect. The IDE hints "cannot find symbol Object".

What correction do I need to apply in returnSomething's body to compile successfully?

CodePudding user response:

Object is just the name of the class.

Object.class is the instance of the Class<Object> class that represents the Object class. See Class.

So you need:

return Object.class;

CodePudding user response:

Your return type is incorrect in your method. You need to understand that this '.class' is used in Java for code Reflection. Generally you can gather meta data for your class such as the full qualified class name, list of constants, list of public fields,etc... So in your example you are basically saying that the Class type to be returned for the wildcard used will either be Object or Subclass of object to be returned at Runtime. Note that you want Java to determine the object returned at Runtime.

  • Related