1

I have declared a method that return Class, but i don't know if it is the right way or not . When i pass int, float, double or String as parameter, i want to return int.class, float.class or double.class.

How can i do that?

Class<?> analyseType(String nameType) throws ClassNotFoundException {
        Class<?> classe = Class.forName(nameType);
        return classe; 
    }
Gismail
  • 89
  • 10
  • 1
    From [the documentation](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Class.html#forName(java.lang.String,boolean,java.lang.ClassLoader)): "_If `name` denotes a primitive type or void, an attempt will be made to locate a user-defined class in the unnamed package whose name is `name`. Therefore, this method cannot be used to obtain any of the Class objects representing primitive types or void_". – Slaw Apr 18 '20 at 22:10
  • I still have a problem with String , when I have an input as "String", how should i do ? – Gismail Apr 18 '20 at 22:22
  • 1
    The `Class.forName` method expects a fully qualified name and, despite its special treatment, `String` is _not_ a primitive type. You should pass "java.lang.String". – Slaw Apr 18 '20 at 22:23

0 Answers0