简体   繁体   English

将通用方法C#的类型设置为Java

[英]Set the type for generic method C# to Java

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. 我刚刚再次开始使用Java进行编码,并且正在将一些代码从C#转换为Java以用于一个小型项目,以再次开始使用Java。 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: 在C#中,我将执行以下操作:

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. 如上所述,我可以根据变量classType检索ClassA的不同实现。 However, in Java I cannot do (or atleast the Netbeans 8.0 IDE signals error when doing it) the same. 但是,在Java中,我做不到(或至少在执行NetBeans 8.0 IDE信号时出错)。 Basically I cannot tell the method what type I want back (call below is what I want in java): 基本上我不能告诉该方法我想要返回什么类型(下面的调用是我想要的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) (更像是,方法内部应该是什么T)

Might be diffuse, not an expert in expressing myself properly, haha. 可能会分散,而不是正确表达自己的专家,哈哈。 All help appreciated! 所有帮助表示赞赏!

您只需要将通用信息放在Java的其他位置即可:

return classToBeCloned.<ClassB>CreateClone();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM