У меня есть родительский класс, Parent
, с двумя дочерними классами, A
и B
.Есть класс Wrapper
, который содержит интерфейс Function
, который позволяет программисту указывать конкретный метод для каждой оболочки.
Wrapper
содержит переменные Class<Parent> inputClass
и Class<Parent> outputClass
, которые определяют тип ввода и вывода.Wrapper
должен отобразить A на A или B или B на A или B.
Моя проблема возникает, когда я пытаюсь вызвать конструктор-обертку, Wrapper(Class<Parent> input, Class<Parent> output, Function func)
.Eclipse дает мне ошибку за попытку вставить A.class
или B.class
для input
или output
.Учитывая, что A и B являются дочерними классами Parent, я думал, что они смогут перейти в конструктор.Как я могу это реализовать?
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;
}
});
}
}