In: Computer Science
Suppose we have a Java class called Person.java
public class Person
{
private String name;
private int age;
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
public String getName(){return name;}
public int getAge(){return age;}
}
(a) In the following main method which lines contain reflection calls?
import java.lang.reflect.Field;
public class TestPerson
{
public static void main(String args[]) throws Exception
{ Person person = new Person("Peter", 20);
Field field = person.getClass().getDeclaredField("name"); field.setAccessible(true);
field.set(person, "Paul");
}
} (
b) Describe what the reflection commands in (a) above do and why it might be a concern to object-oriented programming purists.
(a) .person.getClass().getDeclaredField("name");
(B). Java Reflection provides ability to inspect and modify the runtime behavior of application. Reflection in Java is one of the advance topic of core java. Using java reflection we can inspect a class, interface, enum, get their structure, methods and fields information at runtime even though class is not accessible at compile time. We can also use reflection to instantiate an object, invoke it’s methods, change field values.
We should not use reflection in normal programming where we already have access to the classes and interfaces because of following drawbacks.
Poor Performance – Since java reflection resolve the types dynamically, it involves processing like scanning the classpath to find the class to load, causing slow performance.
Security Restrictions – Reflection requires runtime permissions that might not be available for system running under security manager. This can cause you application to fail at runtime because of security manager.
Security Issues – Using reflection we can access part of code that we are not supposed to access, for example we can access private fields of a class and change it’s value. This can be a serious security threat and cause your application to behave abnormally.
High Maintenance – Reflection code is hard to understand and debug, also any issues with the code can’t be found at compile time because the classes might not be available, making it less flexible and hard to maintain.