문제

I just started coding in Java again and I'm converting some code from C# into Java for a small project, to get started in Java again. My problem is with how to specify what type of instance I want back from a generic method. In C# I'd do something like this:

const int B = 1;
const int C = 2;
int classType = a given value
ClassB : ClassA
ClassC : ClassA

private ClassA CreateClone(ClassA classToBeCloned){
    switch(classType){
        case B:
            return classToBeCloned.CreateClone<ClassB>(); 
        case C:
            return classToBeCloned.CreateClone<ClassC>();
    }
    return null;
}

And as such as above I can retrieve different implementations of ClassA depending on the variable classType. However, in Java I cannot do (or atleast the Netbeans 8.0 IDE signals error when doing it) the same. Basically I cannot tell the method what type I want back (call below is what I want in java):

classToBeCloned.CreateClone<Class*>();
Where * = B or C

So how do I specify what type the method should send back? (More like,what T should be inside the method)

Might be diffuse, not an expert in expressing myself properly, haha. All help appreciated!

도움이 되었습니까?

해결책

You just need to locate the generic information at a different spot for Java:

return classToBeCloned.<ClassB>CreateClone();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top