How can I use a string to search for a class with the same name with a string

So, suppose I have a string str = "MyClass", now I want to use this string to find MyClass so that I can create and use it.

+3
source share
3 answers

A simple example:

MyClass obj = Class.forName("com.xyz.MyClass").newInstance();

This assumes the existence of a default constructor and will throw various exceptions if the class cannot be found or cannot be created.

+5
source

Class.forName can do what you want, but you also need the full package path.

0
source

myclass= Class.forName ( "package.MyClass" );

instance = myClass . newInstance();

package - , MyClass

0

Source: https://habr.com/ru/post/1777525/


All Articles