You can try a method called Reflection
Reflection in Java is used to view information about classes, interfaces, methods, fields, constructors, annotations during the execution of java programs. At the same time, it is not necessary to know the names of the elements studied in advance.
All classes for working with reflection are located in the java.lang.reflect .
With the help of reflection you can
- Get information about class modifiers, fields, methods, constants, constructors, and superclasses.
- Call an object method by name.
- Find out which methods belong to the interface / interfaces being implemented. Create an instance of the class, and the name of the class is unknown until the execution of the program.
- Get and set the value of an object field by name.
- Learn / define object class
- other
Example:
MyClass obj = new MyClass(); // <--- это класс, который будем просматривать Class c = obj.getClass(); // Получение объекта типа Class Method[] methods = c.getDeclaredMethods(); // возвращаем все методы класса не зависимо от типа доступа for (Method method : methods) { System.out.println("Имя: " + method.getName()); System.out.println("Возвращаемый тип: " + method.getReturnType().getName()); Class[] paramTypes = method.getParameterTypes(); // берем параметры метода System.out.print("Типы параметров: "); for (Class paramType : paramTypes) { System.out.print(" " + paramType.getName()); } System.out.println(); System.out.println("------------------------"); } // Пример получения конкретного метода по имени Method method1 = с.getMethod("simple"); // Вызвать метод с помощью invoke - передать туда только объект String simple = (String)method1.invoke(c);
If we do not know the name of the class at the time of compilation, but we know it at runtime, we can use the forName() method to get the Class object.
Class obj = Class.forName("com.test.classes.MyClass");
Also instead
MyClass obj = new MyClass(); // <--- это класс, который будем просматривать Class c = obj.getClass(); // Получение объекта типа Class
You can write:
Class obj = MyClass.class;
Those. you do not need to create an instance of the class (which can call the constructor and rotate unknown manipulations), and we already know at the time of compilation what type it will be.