Is it possible to have the Object return it’s Class name? I’m trying to use the .Class name as a key for a hash map and have it store every object under that Class.
I tried Casting the object to Class, but unfortunately that returned an error. Any help would be appreciated!
anything.getClass().getName()
if your going to use a hashmap do it like this:
HashMap<String, yourClass> map = new HashMap<String, yourClass>();
then in your class have a method that returns the name:
private final String NAME;
public yourClass(String name)
{
NAME = name;
{
public String getName()
{
return NAME;
}
then do this:
YourClass class = new yourClass(“name”);
map.put(class.getName(), class);
[edit] Then for searching for the class you want do something like this:
public yourClass findClass(String name)
{
yourClass class = (yourClass) map.get(name);
return class;
}
of course this is all pseudo code.
Ehhhh what’s the point of that method? There is no need to cast…
Also, “class” is a reserved keyword, you cannot use it
Anyway, Riven’s method is better
I said it was pseudo code… and I always add the cast just in case (it is a HashMap were talking about here) it also throws an error if it can’t cast so you can catch it and do something about it, I never design my programs to have to use that but it is nice to have anyway.
Just in case what? Generics don’t suddenly “not work”
Thanks guys! Appreciate the quick help!
In reverse way, there’s also “instanceof”.