0

I have this code:

ObjProcessor processor = getProcessor();
MyClass myObj = getObjToProcess();// MyClass extends PersistentObj

and classes:

public class ObjProcessor {
   public <OP extends PersistentObj) void process(Class<OP> objClazz, OP object, Modifier<OP> modifier) {
     ...
   }
}
public interface Modifier<T> {
    void modify(T obj);
}

I am stuck. How do I create an instance of the Modifier to be able to invoke:

processor.process(myObj.getClass(), myObj, ???);

After Ron C's comment, I created this Modifier:

 Modifier<MyClass> mod = new Modifier<MyClass>() {
    @Override
    public void modify(MyClass obj) {
       // empty
    }
}; 

proc.process(myObj.getClass(), myObj, mod); // compilation error!

Eclipse gave this error:

The method process(Class<OP>, OP, Modifier<OP>) in the type ObjProcessor is not applicable for the arguments (Class< capture#1-of ? extends MyClass>, MyClass, Modifier<MyClass>)
8xomaster
  • 165
  • 8

1 Answers1

0

You can create an anonymous inner class as an instance of the Modifier interface:

processor.process(myObj.getClass(), myObj, new Modifier<MyClass>() {

    @Override
    public void modify(MyClass obj) {
        //Add implementation here
    }
});

If you're using java 8, you can also use lambada expressions. Because your interface is considered as a Functional Interface (interface with only one method), you can use lambada expression instead of creating anonymous class:

processor.process(myObj.getClass(), myObj, obj -> {
    //Add implementation here
});

For the second problem, the solution is to change the declaration of process to:

public <OP extends ObjProcessor> void process(Class<? extends OP> objClazz, OP object, Modifier<OP> modifier) {

}

I've replaced Class<OP> with Class<? extends OP>. The older decleration only works with: MyClass.class, but not with: instanceOfMyClass.getClass().

The reason for this is that the Class<OP> type argument can't accept Class<ClassExtendsOP> as an argument, it's only allow one class.

If your'e using MyClass as OP, when you're using MyClass.class, you're always getting Class<MyClass> object. But when you're using instanceOfMyClass.getClass(), you can get Class<ClassExtendsMyClass>, which not match the argument type.

Ron C
  • 1,116
  • 9
  • 11