views:

293

answers:

2

For example when I have a class named;

'MonkeyBusiness'

I know I can call it using Class.forName("MonkeyBusiness");

But when I call it using Class.forName("monkeyBusiness"); or Class.forName("monkeybusiness"); it gives me the exception;

Exception in thread "main" java.lang.NoClassDefFoundError: monkeyBusiness
(wrong name: ntx/gmd/services/usage/MonkeyBusiness)

Is it possible to call it using any case-formatted string? If so, how?

+8  A: 

You don't.

Monkey monkey and MONKEY are three totaly different things in Java.

Why do you need such a function? The root problem might be that you don't know which classes are relevant within your application.

There are two things you can do. First, have an internal convention that you only use lowercase or CamelCase class names. In this way, just convert your search to the appropriate format: Class.forName(className.toLowerCase())

Secondly, you can make a cache of all used classes, and look the appropriate name up from cache. Just make a list with the lowercase name as the key, and the real name as the value.

Thirdly, but not recommended, brute force check all combinations. But this creates an awfully bad scaling function for longer names: 2^n, for n-length names.

Gerrit
+3  A: 

You can write a ClassLoader that ignores case. Java ClassLoaders basically only support one function: a client can say "Here's a String, please load the class with that name", and the ClassLoader either replies "Sorry, I don't know the class", or "Yes, here is the class". How the ClassLoader implements this behavior is complete up to its implementer.

Michael Borgwardt
Do you have an example of a custom ClassLoader?
MrThys
http://www.google.de/search?q=java+"custom+classloader"+tutorial
Michael Borgwardt