简体   繁体   English

如何使用通用类检查类的有效性

[英]How to check class validity with generic class

I'm working on code where I have to cast base class onto derived one where I have an array of generic types that are derived by the base on. 我正在研究必须将基类转换为派生类的代码,在派生类中,我有一组由基类派生的泛型类型。

For example, I have Base and Derived1, Derived2 and I put them into Class[]{Derived1.class, Derived2.class} and I pass this array to the constructor of the class. 例如,我有Base和Derived1,Derived2,并将它们放入Class [] {Derived1.class,Derived2.class}中,然后将此数组传递给类的构造函数。

In this constructor, I have to create instances of these derived classes and I don't know how to do that because I get the info that Class and Base are incompatible. 在此构造函数中,我必须创建这些派生类的实例,但我不知道该怎么做,因为我得到了Class和Base不兼容的信息。

Here is my code example 这是我的代码示例

public abstract class Base {
public abstract Base create(String s);
}

public class Derived extends Base {
java.lang.Integer value;
private static Derived integer = new Derived();

public static Derived getInstance(){
    return integer;
}

public Base create(String s) {
    value = java.lang.Integer.parseInt(s);
    return this;
}
}

public class Clazz {
Class<? extends Base> type;
ArrayList<Base> arrayList;

public Class<? extends Base> getType() {
    return type;
}
}


public class AnotherClazz{

ArrayList<Clazz> clazzArrayList;
Class<? extends Base>[] types;

AnotherClazz(Class<? extends Base>[] args){
    clazzArrayList = new ArrayList<>();
    types = args; // assuming I pass 2 elements in array
    String[] strings = new String[]{"1","2"};
    for (int i=0; i<args.length; ++i){
        if (types[i] instanceof Base){
            // here i want to check validity of class
        }
    }

    for (int i=0; i<strings.length; ++i){
        clazzArrayList.get(i).arrayList.add(((types[i]) Base).getInstance().create(strings[i])); 
    //here i want to create instance of object from type assigned to specific column
    }
}

Thanks for the help. 谢谢您的帮助。

要检查有效性,请尝试此

if (types[i].getClass().isAssignableFrom(Base.class))

If I read the question correctly, you want to create a few instances of derived classes that all have the same constructor arguments. 如果我正确阅读了该问题,则您想创建一些派生类的实例,这些实例都具有相同的构造函数参数。 If that is the case, then you need to give each derived class the same constructor (it does not need to be in the base class) and use Constructor.newInstance(parameters) to create the instances. 如果是这种情况,则需要为每个派生类提供相同的构造函数(它不必在基类中),然后使用Constructor.newInstance(parameters)创建实例。 Further, since you want to ensure that each derived class extents the base class then you will want to use Class.isAssignableFrom(class). 此外,由于要确保每个派生类都可扩展基类,因此您将要使用Class.isAssignableFrom(class)。 For example, 例如,

import java.lang.reflect.Constructor;

public class SO52930530 {

    public abstract static class Base {

        public abstract <T> T getValue();
    }

    public static class Derived1 extends Base {

        String value;

        public Derived1(String value) {
            this.value = value;
        }

        public <T> T getValue() {
            return (T) value;
        }
    }

    public static class Derived2 extends Base {

        Integer value;

        public Derived2(String value) {
            this.value = new Integer(value);
        }

        public <T> T getValue() {
            return (T) value;
        }
    }

    public static void main(String... args) throws Exception {

        Class<? extends Base>[] extensions = new Class[]{Derived1.class, Derived2.class};
        String[] values = new String[]{"a", "1"};
        Base[] instances = new Base[values.length];

        for (int i = 0; i < instances.length; i++) {
            Class extension = extensions[i];
            if (Base.class.isAssignableFrom(extension)) {
                Constructor constructor = extension.getConstructor(String.class);
                instances[i] = (Base) constructor.newInstance(values[i]);
            }
        }

        for (int i = 0; i < instances.length; i++) {
            System.out.printf("%d %s %s\n", i, instances[i].getClass(), instances[i].getValue());
        }
    }
}

I hope this helps. 我希望这有帮助。

Thanks for helping with checking validity (it works!) but I still don't get this newInstance creation because I have to read data from .csv file and my derived classes are in fact "wrappers" for primitive types like int, float, etc. and I am supposed to create new object using methods getInstance() and create(string s), so it looks like this: 感谢您帮助检查有效性(它可以工作!),但我仍然无法获得newInstance的创建,因为我必须从.csv文件中读取数据,而我的派生类实际上是诸如int,float等原始类型的“包装器”我应该使用方法getInstance()和create(string s)创建新对象,所以它看起来像这样:

public static class Derived1 extends Base { //Integer wrapper

    Integer value;

    public Derived1(Integer value) {
        this.value = value;
    }

    private static Integer integer = new Integer();

    public static Integer getInstance(){
        return integer;
    }

    private Integer(){};

    public Base create(String s) {
        value = java.lang.Integer.parseInt(s);
        return this;
    }

}

and I don't know how to use Class to cast to appriopriate type. 而且我不知道如何使用Class强制转换为适当的类型。

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

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