-
ReflectionStaticPL/JAVA 2019. 8. 27. 08:40
1. Overview
It stands for modifying or examing the behavior of methods, classes, and interfaces at runtime.
- java.lang.reflect packages required classes for reflection
- It gives us information about the class to which an object belongs and also the methods of that class which can be executed by using the object.
- Being able to invoke methods at runtime irrespective of the access specifier used with them.
- This can violate some policy like singleton using private constructor, and so on.
1.1 Where it used
- IDE e.g. Eclipse, NetBeans, etc.
- Debugger
- Test Tools
- Spring
- Hibernate
2. Usages
Reflection can be used to get information about
2.1 Class
- The getClass() is used to get the name of the class to which an object belongs.
2.2 Constructor
- The getConstructors() is used to get the public constructors of the class which an object belongs and what parameters they take, and etc.
2.3 Methods
- The getMethods() is used to get the public methods of the class to which an object belongs.
2.4 Fields
- If you have a reference to the Class object representing some class, you can see what fields that class contains.
- You can read its name, access modifier, etc.
Class myObjectClass = MyObject.class; Field[] fields = myObjectClass.getFields();
// A simple Java program to demonstrate the use of reflection import java.lang.reflect.Method; import java.lang.reflect.Field; import java.lang.reflect.Constructor; // class whose object is to be created class Test { // creating a private field private String s; // creating a public constructor public Test() { s = "GeeksforGeeks"; } // Creating a public method with no arguments public void method1() { System.out.println("The string is " + s); } // Creating a public method with int as argument public void method2(int n) { System.out.println("The number is " + n); } // creating a private method private void method3() { System.out.println("Private method invoked"); } } class Demo { public static void main(String args[]) throws Exception { // Creating object whose property is to be checked Test obj = new Test(); // Creating class object from the object using // getclass method Class cls = obj.getClass(); System.out.println("The name of class is " + cls.getName()); // Getting the constructor of the class through the // object of the class Constructor constructor = cls.getConstructor(); System.out.println("The name of constructor is " + constructor.getName()); System.out.println("The public methods of class are : "); // Getting methods of the class through the object // of the class by using getMethods Method[] methods = cls.getMethods(); // Printing method names for (Method method:methods) System.out.println(method.getName()); // creates object of desired method by providing the // method name and parameter class as arguments to // the getDeclaredMethod Method methodcall1 = cls.getDeclaredMethod("method2", int.class); // invokes the method at runtime methodcall1.invoke(obj, 19); // creates object of the desired field by providing // the name of field as argument to the // getDeclaredField method Field field = cls.getDeclaredField("s"); // allows the object to access the field irrespective // of the access specifier used with the field field.setAccessible(true); // takes object and the new value to be assigned // to the field as arguments field.set(obj, "JAVA"); // Creates object of desired method by providing the // method name as argument to the getDeclaredMethod Method methodcall2 = cls.getDeclaredMethod("method1"); // invokes the method at runtime methodcall2.invoke(obj); // Creates object of the desired method by providing // the name of method as argument to the // getDeclaredMethod method Method methodcall3 = cls.getDeclaredMethod("method3"); // allows the object to access the method irrespective // of the access specifier used with the method methodcall3.setAccessible(true); // invokes the method at runtime methodcall3.invoke(obj); } }
The name of class is Test The name of constructor is Test The public methods of class are : method2 method1 wait wait wait equals toString hashCode getClass notify notifyAll The number is 19 The string is JAVA Private method invoked
3. Features
3.1 The .class syntax
- If a type is available but no instance then it is possible to obtain a Class by appending ".class" to the name of the type. it can be used for primitive data type so.
class Test{ public static void main(String args[]){ Class c = boolean.class; System.out.println(c.getName()); Class c2 = Test.class; System.out.println(c2.getName()); } }
boolean Test
3.2 invoke()
- Invoking a method of the class at runtime
Method.invoke(Object, parameter) // If the method of the class doesn’t accepts any // parameter then null is passed as argument.
3.3 Invoking regardless of access modifier
Through reflection, we can access the private variables and methods of a class with the help of its class object and invoke the method by using the object as discussed above. below for this purpose
3.3.1 Class.getDeclaredField(FieldName)
- Used to get the private field. Returns an object type Field for a specified field name
3.3.2 Field.setAccessible(true)
- Allows to access the field irrespective of the access modifier used with the field
4. Methods
Method Description public String getName() returns the class name public static Class forName(String className) throws ClassNotFoundException loads the class and returns the reference of Class class. public Object newInstance() throws Instantiation, IllegalAccessException creates a new instance. public boolean isInterface() checks if it is an interface public boolean isArray() checks if it is an array. public boolean isPrimitive() checks if it is primitive public Class getSuperclass() returns the superclass class reference public Field[] getDeclaredFields() throws SecurityException returns the total number of fields of the class
public Method[] getDeclaredMethods() throws SecurityException returns the total number of methods of this class. public Consructor[] getDeclaredConstructor() throws SecurityException returns the total number of constructors of this class. public Method getDeclaredMethod(String name, Class[] parameterTypes) throws NosSuchMethodException, SecurityException returns the method class instance 5. Pros and Cons
3.1 Advantages
- Extensibility Features
- An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names
- Debugging the and testing tools
- Debuggers use the property of reflection to examine private members in classes.
3.2 Drawbacks
- Performance Overhead
- Reflective operations have slower performance than their non-reflective counterparts and should be avoided in sections of code which are called frequently in performance-sensitive applications
- Exposure of Internals
- Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.
6. References
https://docs.oracle.com/javase/tutorial/reflect/index.html
https://www.geeksforgeeks.org/reflection-in-java/
https://www.javatpoint.com/java-reflection
https://www.baeldung.com/java-reflection
http://tutorials.jenkov.com/java-reflection/index.html
http://www.java2s.com/Tutorials/Java/Java_Reflection/0020__Java_java.lang.Class.htm
'StaticPL > JAVA' 카테고리의 다른 글
Functional (0) 2019.08.27 Generics and Generic Methods (0) 2019.08.27 Checked and Unchecked Exceptions (0) 2019.08.23 Fork Join framework (0) 2019.08.23 Garbage Collection (GC) (0) 2019.08.23