Generics and Dynamic Instantiation Problem
Can anyone help me to fix the code in the Main so that is works as intended?
Gurus will know what I'm after.
TIA :cool:
Please see below:
Code Java:
public abstract class MyBaseElement
{...}
public class MyElementA extends MyBaseElement
{...}
public class MyElementB extends MyBaseElement
{...}
public class MyElementC extends MyBaseElement
{...}
public interface Mapper<T>
{...}
public class MyMapperA implements MyMapper<MyElementA>
{...}
public class MyMapperB implements MyMapper<MyElementB>
{...}
public class MyMapperC implements MyMapper<MyElementC>
{...}
// this method returns an instance of
// one of the child classes: MyElementA, MyElementB, MyElementC, etc...
Code Java:
public MyBaseElement getSpecificElement() {...}
// this method returns a specific mapper based on the element
Code Java:
public Mapper<? extends MyBaseElement> getSpecificMapper(MyBaseElement element)
{
if (element instanceof MyElementA) return new MyMapperA;
if (element instanceof MyElementB) return new MyMapperB;
if (element instanceof MyElementC) return new MyMapperC;
...
}
Code Java:
// Main
...
MyBaseElement element = getSpecificElement();
// the line below compile
Class<? extends MyBaseElement> myElement = element ;
//the line below does not compile: can not convert from MyBaseElement to Mapper<? extends MyBaseElement>
// Any ideas, please?
Mapper<? extends MyBaseElement> myMapper = getSpecificMapper(myElement )
myMapper.doStuff();
...
// end-Main
Re: Generics and Dynamic Instantiation Problem
Quote:
Originally Posted by marcosmarcos
Can anyone help me to fix the code in the Main so that is works as intended?
Gurus will know what I'm after.
I have no idea what you are after.
Firstly I would recommend posting something we can compile.
Secondly, please give us an indepth description of your problem.
Re: Generics and Dynamic Instantiation Problem
I agree with JavaPF here, somewhat confusion this.
However, I'm not sure this will work, into the method getSpecificMapper you're passing in a Class<? extends MyBaseElement> but in the method signature it takes a MyBaseElement, not a Class.
// Json