Group: comp.lang.java.programmer
From: ram@zedat.fu-berlin.de (Stefan Ram)
Date: Sunday, February 24, 2008 10:14 PM
Subject: Re: How to create an instance of type T?

prowyh writes:
>Thanks for all of your responses. I'm frustrated that it is impossible
>to create an instance of type T due to the type erasure of Java.

You can move the type parameter to »InputClass«, name a
subclass and then read the actual type argument at runtime:

class B< T >{ /* ... */ }

class C extends B< java.lang.Double >{}
class D extends B< java.lang.Integer >{}
class E extends B< java.lang.Character >{}

public class Main
{ public static void main( final java.lang.String[] args )
{ java.lang.System.out.println
( ( ( java.lang.reflect.ParameterizedType )
C.class.getGenericSuperclass() ).
getActualTypeArguments()[ 0 ]); }}

class java.lang.Double

An early text expressing this idea is:

http://gafter.blogspot.com/2006/12/super-type-tokens.html

In



Ralf Ullrich presents two other ideas for the same purpose.

With reflection, you then can create instances of this type,
if they have an appropriate constructor with a string
argument.

However, I don't think I would do this, for what you want
to do.

>public Double getDoubleValue()
>It's almost useless and very ugly!

I believe this still is not what you actually want to achieve.

If the type of the number is given by the input, then use
a factory method, like:

Value value = getNextValue();

Where »Value« is the supertype of all possible types.

If the type of the number is given by your expectation,
then use this. For example, if you expect a double, use

Double d = getNextDouble();

If the type is given neither by the input nor by the
expectation of the source code, how is it given, then?

Java has static typing, which sometimes gets in the way and
requires some redundancy in the source code (like
»getNextDouble«, »getNextInt«, ...). This is not considered
ugly in Java. See

http://download.java.net/jdk7/docs/api/java/util/Scanner.html
http://download.java.net/jdk7/docs/api/java/util/Arrays.html

.--------------------------------------------------.
| When one has chosen Java, one wants it this way. |
'--------------------------------------------------'

Otherwise one would have chosen Ruby or so.

News in English | Binaries Groups | 20lbs in 30 days