Re: enum/generics typesafe getter for generic types
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
visionset schreef:
"Piotr Kobzda" <pikob@gazeta.pl> wrote in message
news:eumvuj$1in$1@inews.gazeta.pl...
visionset wrote:
Yes, but how do I now use this class to form a generic getter outside of
Key class?
For this kind of call:
String s = foo.get(Key.A_KEY);
because I'm not instantiating Key, I can't pass in a <Type> so I can't
form a generic method.
You can, declare it e.g. like that:
public <T> T get(Key<T> key) { ...
But I think there is a T resolution issue outside the Key class.
public class Preference {
public static final Key<String> A_KEY = new Key<String>();
public static final Key<String> B_KEY = new Key<String>();
public static final Key<Integer> C_KEY = new Key<Integer>();
public static final Key<Integer> D_KEY = new Key<Integer>();
public static class Key<T> {
// how to get T outside of Key class?
You can???t. But generally, you will have instantiated a Key<Something>
yourself, so you will know what Something is.
}
private Map<Key, T> map; // how to define this?
You will want to give a generic parameter to Key as well. If you have
nothing better, use Object or even <?>. Using T there will only work if
T is defined in Preference, which it isn???t. You will need Object and
casting, as in Piotr???s example.
public <T> T get(Key<T> key) {
// what goes here
Whatever you want.
return map.get(T);
This is impossible. You cannot use types as parameters. Think of it as
get.(Integer). That doesn???t make sense either. The closest to it is
get(Integer.class), since Integer.class is an object of type
Class<Integer>. But get(T.class) will not work, since T cannot be
resolved at compile time.
}
public void testGet() {
String s = get(A_KEY);
}
HTH, H.
- --
Hendrik Maryns
http://tcl.sfs.uni-tuebingen.de/~hendrik/
==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.5 (GNU/Linux)
iD8DBQFGENXve+7xMGD3itQRAuNaAJ4orejOfE5rKYFDsbn3H+7w/abjXQCeLTXY
lJOkgv5fhBmiDwDaGZmg3JY=
=hMxf
-----END PGP SIGNATURE-----