简体   繁体   中英

JAVA: Generic type compile time constant

I have an abstract generic class which requires a numeric constant to initialize an array. I know the size of array at compile time when I use that generic class. Is there any way to implement this?

abstract class Node<T, MagicN> {

    private T parent    = null;
    private T[] child   = (T[]) new Object[MagicN];

    //some methods that rely on the initialized array.

}
final class ConcreteNode extends Node<ConcreteNodeType, 2> {

}

The class ConcreteNode has 2 children in this example.

You can't use a Generic as a template. As Java's code optimisation is done at runtime, there is little reason to have such compile time inlining.

abstract class Node<T extends Node> {

    private final T parent;
    private final T[] child;

    Node(T parent, int size) {
        this.parent = parent;
        child = (T[]) new Object[size];
    }

    //some methods that rely on the initialized array.

}
final class ConcreteNode extends Node<ConcreteNode> {
     ConcreteNode(ConcreteNode parent) {
         super(parent, 2);
     }
}

You can't have values instead of a generic type (or you should have to create a class for each value you may use...)
I think the best in your case would to have a constructor that takes this value as a parameter for example :

abstract class Node<T> {

    private T parent    = null;
    private int MagicN = 0;
    private T[] child   = null;

    protected Node(int MagicN)
    {
        this.MagicN = MagicN;
        this.child = (T[]) new Object[MagicN];
    }

    //some methods that rely on the initialized array.

}

final class ConcreteNode extends Node<ConcreteNodeType> {
    public ConcreteNode()
    {
        super(2);
    }
}

In terms of performance, there is no difference between what you are trying to do and this example since your child array is initialized in an object context and not a static one.

Why not do it this way?

abstract class Node<T> {
    private T parent    = null;
    private T[] child;

    public Node(int childCount) {
        child = (T[]) new Object[childCount];

    //some methods that rely on the initialized array.

}
final class ConcreteNode extends Node<ConcreteNodeType> {
    public ConcreteNode()
    {
        super(2);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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