Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing variable. I don't know their type [java]

Tags:

java

generics

class pair<U,V>{
U first;
V second;
public pair() {
    first = new U(); //error
    second = new V(); //error
}   
public pair(U f,V s){
    first = f;
    second = s;
}
}

required: class
found: type parameter

Is it possible to initialize first/second with (without-arguments) constructor of U/V type other way?

like image 445
RiaD Avatar asked Jul 16 '11 15:07

RiaD


People also ask

How do you initialize a variable in Java?

int x = 10 ; This creates a box called x with type int and writes a value of 10 in the box. The syntax for an initializer is the type, followed by the variable name, followed by an equal sign, followed by an expression. That expression can be anything, provided it has the same type as the variable.

Can variables be used in Java without initialization?

If you declare a final variable later on you cannot modify or, assign values to it. Moreover, like instance variables, final variables will not be initialized with default values. Therefore, it is mandatory to initialize final variables once you declare them.

Does Java automatically initialize all variables?

Java does not initialize non-array local variables (also referred to as automatic variables) . The Java compiler generates error messages when it detects attempts to use uninitialized local variables. The Initializer program shows how automatic initialization works.

How do you initialize a variable only once in Java?

Static variable in Java is variable which belongs to the class and initialized only once at the start of the execution. It is a variable which belongs to the class and not to object(instance ). Static variables are initialized only once, at the start of the execution.


1 Answers

Java does not normally allow this because of type erasure. You can specify constructor arguments of type Class<U> and Class<V>, for which you would pass in concrete class types of the given type parameters (i.e., Integer.class and String.class for <Integer> and <String>).

It is also possible to extract the type using bytecode-level reflection, but quite complicated, and it doesn't always work in all situations. If you scroll down on this article, you can find the example that makes this possible. I've pasted it below for convenience.

static public Type getType(final Class<?> klass, final int pos) {
    // obtain anonymous, if any, class for 'this' instance
    final Type superclass = klass.getGenericSuperclass();

    // test if an anonymous class was employed during the call
    if ( !(superclass instanceof Class) ) {
        throw new RuntimeException("This instance should belong to an anonymous class");
    }

    // obtain RTTI of all generic parameters
    final Type[] types = ((ParameterizedType) superclass).getActualTypeArguments();

    // test if enough generic parameters were passed
    if ( pos < types.length ) {
        throw RuntimeException(String.format("Could not find generic parameter #%d because only %d parameters were passed", pos, types.length));
    }

    // return the type descriptor of the requested generic parameter
    return types[pos];
}

Edit: for reply to comment:

class pair<U,V>{
    U first;
    V second;
    public pair(Class<U> cu, Class<V> cv) {
        try {
            first = cu.newInstance();
            second = cv.newInstance();
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }   
    public pair(U f,V s){
        first = f;
        second = s;
    }
}
like image 90
Chris Dennett Avatar answered Oct 22 '22 04:10

Chris Dennett