1

I have an enum and try to get another Class with Class.forName(example)

However, It displays ClassNotFoundException. My question is this, how can I throw an exception to solve this?

Example Code

enum Example {
  PLUS("Plus", new Class<?>[]{Class.forName("com.directory.File")})
}
TheCoder
  • 128
  • 12
  • Can you include some code that demonstrates the problem? – Sean Bright Oct 14 '19 at 14:29
  • You want to throw a ClassNotFoundException to resolve that exception?? You have not described the issue, please edit your question – Ioannis Barakos Oct 14 '19 at 14:30
  • 1
    See also [How to throw an exception from an enum constructor?](https://stackoverflow.com/questions/3543903/how-to-throw-an-exception-from-an-enum-constructor). But the best approach is to *not throw an exception* in the initialization of an enumerator. Do you have a class whose name is "file", beginning with a lower-case letter, in the namespace "com.directory"? – Andy Thomas Oct 14 '19 at 14:37
  • Thanks @AndyThomas I will check it... – TheCoder Oct 14 '19 at 14:37
  • do you really need to get that class there dynamically? Isn't just using `com.directory.File` class solving your real usecase? Because, when this dynamic access happens inside a static initializer as in your case, I don't see how it could be useful – Petr Kozelka Oct 14 '19 at 14:38
  • It is not solving the issue because they do not want me to use a new dependency at the module @PetrKozelka – TheCoder Oct 14 '19 at 14:40
  • 1
    @TheCoder ok; still, this way, the dependency is there, only in a form hidden from the buildsystem (not even from the compiler), which quite always leads to somewhat twisted code. If maven is your buildsystem, consider instead using `optional` flag in a sample dependency. – Petr Kozelka Oct 14 '19 at 15:26

3 Answers3

2

You could avoid throwing the exception from the enumerator at all.

enum Example {
  PLUS("Plus", new String[]{"com.directory.File"});
  ...
}

public class ExampleFactory {
  List<Class<?>> getClassesForExample( Example example ) throws ClassNotFoundException {
      // Build list of classes from class names in enumerator.
      ... 
  }
}
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
0

Use try-catch:

try {
   Class<?> clazz = Class.forName(example);
   ...
} catch (ClassNotFoundException ex) {
   ... 
}
Miosotaa
  • 23
  • 1
  • 11
0

You can catch exception by this way:

enum Example {   
        PLUS("Plus", Example("com.directory.file"));

        Example (String plus, Class<?>[] example) { }

        private static Class<?>[] Example (String className){
            try {
                return new Class<?>[]{Class.forName(className)};
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            return null;
        }
}
Miosotaa
  • 23
  • 1
  • 11