I am trying to set a static String class variable equal to the name of the class. I do not want to use a constant as the entire purpose for doing this is to allow the class to be renamed without having to change the variable's value. Can I use Class' methods to do this even though I do not have an instance of the class? If not, is there another way to accoumplish this short of setting the variable in the constructors?
Hi Ron, Welcome to JavaRanch. Umm, not totally clear on what you want here so I'll throw some code at you and see if I'm on the same page with you:
Now that's not groundbreaking code, for one thing the getObjectByName() method can only return an instance of a class that has a public default constructor. But it does demonstrate that with reflection, it is possible to create an instance if all you have is the name of the class. Also to do anything to our instantiated classes, we still will need to typecast them to the proper type which can't be done with a String, we need to know the class at compile time. Michael Morris
Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Hmm, I'm apparently not on the same page here. . Good hack Chris and James, I wouldn't have thought of trying that. It seems to show a deficiency in Reflection though: that one must resort to unconventional means to get the enclosing class from a static context. Michael Morris
hi Ron, sorry but i'm not able to understand the "need" of what you are trying to do. why one would need to know the class name w/o creating any instance of it? also, if you don't want to instantiate an object unnecessarily to know the class name then i would say the approach via throwing an exception doesn't buy us anything. does it? because we endup creating instance of the Throwable. regards maulin
Joined: Jun 18, 2001
For the record, I agree with Maulin. I just thought it was a challenge to get the classname from a static context, I'd never want to write code like I suggested above. I'm guessing that Ron wants the String classname to be a member of his class so that elsewhere in his app he can refer to it. But Ron should really just use obj.getClass().getName() wherever else in the app he was planning on using obj.name. It can't always be used in a static context... can it?