Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

True java generics (templates)

After taking a look in the Java VM specification, I noticed that a lot more than just ASCII letters could be used to create an identifier.

Firstly, I was wondering if there were any extra symbols (apart from $, that are available for identifiers)

Do you think it would be possible, with the extended character set to encode additional information in an identifier, and a custom classloader, to implement true Java generics?

Of course, you would have to get around type erasure, but that could be possible with a custom parser?

So you could store generic names in a format like: $g$GenericList$_Java_lang_String$

I'm using GenericList here as I don't intend to modify the original implementation!

Load them in with the class loader, create a proper GenericList<String> version and send it back.

EDIT: I plan to use this for a language I'm building on the JVM. As it uses $'s and _'s as special characters, encoding information like that might just work!

EDIT 2: I suppose the more difficult thing to do would be generic methods? Does anyone have any information on how those would be implemented?

EDIT 3: Since classes can only be unloaded when the classloader disappears, would I be able to cache and remove resolved templates like it works in .Net, or would I do it like C++?

like image 317
Darkzaelus Avatar asked May 27 '11 10:05

Darkzaelus


1 Answers

The JVM allows any characters in class/field/method names except /, and ; which have a special meaning. Using numbers and other character is common for obfuscators to make de-compiling difficult.

However you could just use the $ and _ for generated class/fields/methods.

Note: JDK 7 is supposed to have better generic support with the Type with a combination of Class and generics.

EDIT:

One way to have proper generic type is to always use

Set<String> set = new LinkedHashSet<String>() { }; 

The use of { } creates an anonymous class which has a parent type with the generic you want. You can get this information via reflection.

You can cache and remove class by having your own class loader which you dispose of as you wish. The most extreme case would be to have a ClassLoader per class.

Once you have your own Generic types, you could just use these in your methods, like normal types.

like image 51
Peter Lawrey Avatar answered Oct 16 '22 09:10

Peter Lawrey