Let’s have an example using Reflection of Constructor ("The return type is void" + m.getReturnType()) ("Modifier is: " + Modifier.toString(modifier)) Method methods = obj.getDeclaredMethods() get all the methods using the getDeclaredMethod() Modifier: private Example: Method Reflection import ĭog d1 = new Dog() // create an object for the Dog class ("Modifier: " + Modifier.toString(modifier)) The class also provides a method getModifier() that returns the modifier of class in integer form.Ī) Program using Get Superclass and Access Modifier import We will use the method getSuperclass(), which can be used to retrieve the information about the superclass of a present class. Let’s learn the example using the Get Superclass and Access Modifier ("Interface Name is: " + cl.getName()) ģ. find the interfaces implemented by DogĬlass objInterface = obj.getInterfaces() create an object of Class using getClass() This method returns an array of interfaces. We will use the getInterfaces() method of the class to collect information about the interfaces implemented by the class. Let’s see the example using the Get Interfaces Method methodcall_3 = cls_1.getDeclaredMethod("method3") Methodcall_2.invoke(obj_t) // invokes the method at runtime Method methodcall_2 = cls_1.getDeclaredMethod("method1") Methodcall1.invoke(obj_t, 19) // invokes the method at runtimeįield field = cls_1.getDeclaredField("str") įtAccessible(true) // allows the object to access the field irrespectiveįt(obj_t, "JAVA") //takes object and the new value to be assigned to the field as arguments Method methodcall_1 = cls_1.getDeclaredMethod("method2", ![]() Method methods_1 = cls_1.getMethods() // Getting methods of the class through the objectįor (Method method1: methods_1) // Printing method names ("The name of constructor is " + constructor_1.getName()) ("The name of class is " + cls_1.getName()) Ĭonstructor constructor_1 = cls_1.getConstructor() TestReflection obj_t = new TestReflection () // Creating object whose property is to be checked Public static void main(String arg) throws Exception Private void method_3() // creating a private method Public void method_2(int number) // Creating a public method with int as argument Public void method_1() // Creating a public method with no arguments Private String str // creating a private field
0 Comments
Leave a Reply. |