Reputation: 327
I have a parent class, Parent
, with two child classes, A
and B
. A have a class, Wrapper
, that contains an interface, Function
, which allows the programmer to specify a particular method for each wrapper.
Wrapper
contains the variables, Class<Parent> inputClass
and Class<Parent> outputClass
, which specify the input and output type. Wrapper
is supposed to map an A to an A or B, or a B to an A or B.
My problem arises when I try to call the wrapper constructor, Wrapper(Class<Parent> input, Class<Parent> output, Function func)
. Eclipse gives me an error for trying to put an A.class
or B.class
in for either input
or output
. Given that A and B are child classes of Parent, I thought they would be able to pass into the constructor. How can I implement this?
public class Parent {
protected int value;
public void setValue(int x){ value = x; }
public int getValue(){ return value; }
}
public class A extends Parent{
public A(){ setValue(1); }
public A(B b){ setValue( b.getValue()); }
}
public class B extends Parent{
public B(){ setValue(2); }
public B(A a){ setValue(a.getValue()); }
}
public class Wrapper{
protected Class<? extends Parent> inputClass;
protected Class<? extends Parent> outputClass;
protected interface Function{
public Parent of(Parent input);
}
protected Function function;
public Wrapper(Class<? extends Parent> in, Class<? extends Parent> out, Function func) {
inputClass = in;
outputClass = out;
function = func;
}
public Parent of(Parent input){
try{
Parent output = function.of( inputClass.getConstructor( input.getClass() ).newInstance(input) );
return outputClass.getConstructor( output.getClass() ).newInstance( output );
} catch(Exception e){
e.printStackTrace();
return null;
}
}
}
public class Main {
public static void main(String[] args){
///Error occurs here. Can't take A.class in for Parent.class
Wrapper wrapper = new Wrapper(A.class,B.class, new Function(){
@Override
public Parent of(Parent p) {
return null;
}
});
}
}
Upvotes: 0
Views: 48
Reputation: 327
The problem wasn't from A.class
or B.class
, but from the interface Function
being nested within the Wrapper
class. I needed to write new Wrapper.Function
in the constructor in main.
Upvotes: 1