Isuru Gunawardana
Isuru Gunawardana

Reputation: 2887

Creating Instance of java classes with file name case Insensitive

Currently I have following method to instantiate objects. I am reading the class name from a file and its in upper case. (I can assume that there won't be many classes like Abc.java, ABC.java or aBc.java and there will be only one class which the name contains a, b, c letters in the given order).

As an example there is a java class named as SchoolPrincipal This class is represented in the file as SCHOOLPRINCIPAL Therefore currently my following method can't find this object due to the uppercase problem and it gives ClassNotFoundException.

I can't rename the java class, it should stays with the standard, and alsoI can't change the word in the file which is in uppercase. Is there a tricky way to solve this problem.

And I have one solution, and want to know the good and bad in this solution, Get all the java classes name and store in a map where the key is all uppercase (key: CLASSTEACHER, Value: ClassTeacher) and when I read the name from file I search it in the map and get the value and pass the className to following method.

public Object getInstance(String packageName, String className)

        String unifiedClassName = packageName + "." + className;
        LOG.info("Creating " + unifiedClassName + " instance...");

        Class<?> clazz = null;
        Constructor<?> ctor = null;
        Object obj = null;

        try {

            clazz = Class.forName(unifiedClassName);
            ctor = clazz.getConstructor();
            obj = ctor.newInstance();

        } catch (InstantiationException e) {
            LOG.error("Error occurred: " + e);
        }
 }

Upvotes: 0

Views: 1160

Answers (1)

Pelit Mamani
Pelit Mamani

Reputation: 2381

Interesting question... I think if you take this approach, the main challenge would be actually getting all available classes in the classpath (IMHO it would still be more efficient than trying all 2^N combinations of names).

Perhaps you're already familiar with classpath scanning, so you omitted it because it was obvious? I was thinking about something like Get all of the Classes in the Classpath, or looking into other 3rd parties that do scanning (e.g. spring or JUnit)

Anyway this would be an interesting thread to follow :)

Upvotes: 2

Related Questions