Method methodCall2 = cls.getDeclaredMethod("method1") Method methodCall1 = cls.getDeclaredMethod("method2", int.class) įield field = cls.getDeclaredField("str") ("\nThe public methods of the class are: ") ("\nThe name of the constructor is: " constructor.getName()) ("\nThe name of the class is: " cls.getName()) Ĭonstructor constructor = cls.getConstructor() ReflectionDemo obj = new ReflectionDemo() Methods: The getMethods() method gives all the public methods of the class to which an object belongs. Constructors: The getConstructors() method returns all the public constructors of the class to which an object belongs.ģ. Class: The getClass() method gives the name of the class to which an object belongs.Ģ. We can use Reflection to get the information about:ġ. True Getting Information using Reflection API Let’s see the example of forName() method to get the instance of the class: class Demo We cannot use this name for primitive types. We should use it only if we know the fully qualified name of the class. This method returns the instance of Class class. The forName() method loads the class dynamically or at runtime. We will discuss each of the methods with an example: 1) The forName() method of Class class There are three ways to get the object of Class class. How can we get the object of Class class? It returns the total number of constructors of this class. Public Constructor getDeclaredConstructors() This method returns the method class instance. Public Method getDeclaredMethod(String name,Class parameterTypes) It returns the total number of methods of the class. It returns the total number of fields in the class. It returns the superclass or parent class reference. This method checks if it is an interface. ![]() This method loads the class and returns the reference of Class. Public static Class forName(String className) It provides methods to examine and change the behavior of the class at runtime.Ĭommonly used methods of the Class class: Method.It provides methods to get the metadata of a class at runtime.Integrated Development Environment(IDEs) such as Eclipse, MyEclipse, NetBeans, etc.The Reflection API of Java is mainly used in: Through reflection, we can call a method at runtime independent of their access specifier.Reflection gives us data about the class with the associated objects and the methods for that class. ![]()
0 Comments
Leave a Reply. |