Automatic creation of Type-Tokens: Is it already there?

The use of Class objects as "type-tokens" is a well-established pattern in Java programming.

It just would be so much nicer if the required Class objects could be automatically supplied by the compiler, woudn't it?

Surprisingly, this feature is already present. The following code shows a class which, if instantiated, automagically receives the correct Class object.

publicclass AutoGeneric<T>{

privatefinal Class<T> type;

@SuppressWarnings("unchecked")

public AutoGeneric(T... argv){

this.type = (Class<T>)argv.getClass().getComponentType();

}

public Class<T> getType(){

return type;

}

publicstaticvoid main(String[] args){

System.out.println(new AutoGeneric<String>().getType());

}

}

What do you think: is that a recommendable way of implementing "automatic type tokens"?

[1514 byte] By [McNeppa] at [2007-11-26 18:54:21]
# 1

I made the same suggestion in this forum last year and got roundly lambasted for my efforts. :-) Although to be fair, my solution need help from the compiler.

My argument was that, just as the compiler provides am implicit 'this' argument as the first argument to all method calls, it should be able to provide n Class<?> arguments for each of the type parameters which you could then usefully query.

dannyyatesa at 2007-7-9 6:28:19 > top of Java-index,Core,Core APIs...
# 2
Well, the above works unless one expects an empty constructor or passes null.If I got it right, Peter Ah?is on a trail to find out how to introduce reifications on generics.
stefan.schulza at 2007-7-9 6:28:19 > top of Java-index,Core,Core APIs...
# 3

I'll blog more about reification later (see http://blogs.sun.com/ahe).

In the meantime, allow me to break the automatic creation of type-tokens idea:

Integer[] ints = { 1 };

Class<Number> cls = new AutoGeneric<Number>(ints).getType();

Number n = cls.cast(1.0);

The last line fails at runtime because cls is really Class<Integer>.

PeterAhea at 2007-7-9 6:28:19 > top of Java-index,Core,Core APIs...