Is there a way to make an array of a user-defined class type in java?

Oct. Lips :

I have a java class Jistthat has two fields, public final Object type and public Object[] content. In the constructor for Jist I want to take in an Object and get its type, then initialize content with some number of empty slots of that type. This is one of the several solutions that I have tried, and the error that I am currently receiving is in the actual initialization of the array:

public class Jist{
public final Object type;
public Object[] content;
public Jist(Object type){
    this.type = type.getClass();
        class myType extends Jist{
            Class c = super.type.getClass();
            public Class getType(){
                return c;
            }
        };
    content = new myType.getType()[4];
}

}

Elliott Frisch :

Make Jist generic on some type T. Pass the Class<T> in the constructor. Use Array.newInstance(Class<?>, int) like

public class Jist<T> {
    public final Class<T> type;
    public T[] content;

    public Jist(Class<T> cls) {
        this.type = cls;
        content = (T[]) Array.newInstance(type, 4);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=367146&siteId=1