Question

In: Computer Science

Suppose we have a Java class called Person.java public class Person { private String name; private...

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.

Solutions

Expert Solution

(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.


Related Solutions

In Java, Here is a basic Name class. class Name { private String first; private String...
In Java, Here is a basic Name class. class Name { private String first; private String last; public Name(String first, String last) { this.first = first; this.last = last; } public boolean equals(Name other) { return this.first.equals(other.first) && this.last.equals(other.last); } } Assume we have a program (in another file) that uses this class. As part of the program, we need to write a method with the following header: public static boolean exists(Name[] names, int numNames, Name name) The goal of...
java programing Q: Given the following class: public class Student { private String firstName; private String...
java programing Q: Given the following class: public class Student { private String firstName; private String lastName; private int age; private University university; public Student(String firstName, String lastName, int age, University university) { this.firstName = fisrtName; this.lastName = lastName; this.age = age; this.university = university; } public String getFirstName(){ return firstName; } public String getLastName(){ return lastName; } public int getAge(){ return age; } public University getUniversity(){ return university; } public String toString() { return "\nFirst name:" + firstName +...
java code ============ public class BankAccount { private String accountID; private double balance; /** Constructs a...
java code ============ public class BankAccount { private String accountID; private double balance; /** Constructs a bank account with a zero balance @param accountID - ID of the Account */ public BankAccount(String accountID) { balance = 0; this.accountID = accountID; } /** Constructs a bank account with a given balance @param initialBalance the initial balance @param accountID - ID of the Account */ public BankAccount(double initialBalance, String accountID) { this.accountID = accountID; balance = initialBalance; } /** * Returns the...
public class StringNode { private String item; private StringNode next; } public class StringLL { private...
public class StringNode { private String item; private StringNode next; } public class StringLL { private StringNode head; private int size; public StringLL(){ head = null; size = 0; } public void add(String s){ add(size,s); } public boolean add(int index, String s){ ... } public String remove(int index){ ... } } In the above code add(int index, String s) creates a StringNode and adds it to the linked list at position index, and remove(int index) removes the StringNode at position...
The Person Class Uses encapsulation Attributes private String name private Address address Constructors one constructor with...
The Person Class Uses encapsulation Attributes private String name private Address address Constructors one constructor with no input parameters since it doesn't receive any input values, you need to use the default values below: name - "John Doe" address - use the default constructor of Address one constructor with all (two) parameters one input parameter for each attribute Methods public String toString() returns this object as a String, i.e., make each attribute a String, concatenate all strings and return as...
I was wondering why my merger class isn't compiling - Java -------------------------------------------------------------------------------------------------------------------- public class Person{ private...
I was wondering why my merger class isn't compiling - Java -------------------------------------------------------------------------------------------------------------------- public class Person{ private String firstName; private String lastName; private int age; private String email; private String phone; private String address;       public Person(String firstName, String lastName, int age, String email, String phone, String address){ setFirstName(firstName); setLastName(lastName); setAge(age); setEmail(email); setPhone(phone); setAddress(address); } public Person(String firstName, String lastName, String email){ setFirstName(firstName); setLastName(lastName); setEmail(email); }    public String getFirstName(){ return firstName; }    public String getLastName(){ return lastName; }...
Write a class called Person that has two private data members - the person's name and...
Write a class called Person that has two private data members - the person's name and age. It should have an init method that takes two values and uses them to initialize the data members. It should have a get_age method. Write a separate function (not part of the Person class) called std_dev that takes as a parameter a list of Person objects and returns the standard deviation of all their ages (the population standard deviation that uses a denominator...
Consider the following class: class Person {         String name;         int age;        ...
Consider the following class: class Person {         String name;         int age;         Person(String name, int age){                this.name = name;                this.age = age;         } } Write a java program with two classes “Teacher” and “Student” that inherit the above class “Person”. Each class has three components: extra variable, constructor, and a method to print the student or the teacher info. The output may look like the following (Hint: you may need to use “super”...
JAVA The class will have a constructor BMI(String name, double height, double weight). The class should...
JAVA The class will have a constructor BMI(String name, double height, double weight). The class should have a public instance method, getBMI() that returns a double reflecting the person's BMI (Body Mass Index = weight (kg) / height2 (m2) ). The class should have a public toString() method that returns a String like Fred is 1.9m tall and is 87.0Kg and has a BMI of 24.099722991689752Kg/m^2 (just print the doubles without special formatting). Implement this class (if you wish you...
package mac286.LinkedLists; public class Postfix { private rStack<String> S; private String inSt; private ourLinkedList<String> inList, outList;...
package mac286.LinkedLists; public class Postfix { private rStack<String> S; private String inSt; private ourLinkedList<String> inList, outList; public Postfix(String s) { S = new rStack<String>(); inSt = s; outList = new ourLinkedList<String>(); inList = new ourLinkedList<String>(); } public void reset(String s) { S = new rStack<String>(); inSt = s; outList = new ourLinkedList<String>(); inList = new ourLinkedList<String>(); } private boolean isOperator(char c) { if(c=='-'||c=='+'||c=='*'||c=='/') return true; return false; } private boolean isParenthesis(char c) { if(c == '(' || c==')') return true;...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT