Harshana
Harshana

Reputation: 7647

How Reflection effects the Design of an application

I have read a some interview questions on java and i found below.

Qus. Is It Good to use Reflection in an application ? Ans. No, It's like challenging the design of application

I need to clarify the above answer more as I learn reflection is a powerful feature of Java.

What is meant by challenging the design?

What scenario we have to practically use reflection in an application?

Upvotes: 2

Views: 64

Answers (1)

Aditya Singh
Aditya Singh

Reputation: 2443

Challenging the design means you can:

  1. Access private members of a class using reflection.
  2. You can instantiate those classes that you are not supposed to, example: you can instantiate java.lang.System using reflection which you are not intended to.
  3. And many other things that the original programmer of the API doesn't want you to. Or you can do things you should not as far as possible.

Though reflection is useful in certain cases:

  1. Like when using FXML, your interpreter dynamically loads the FXML file and sets attributes to your nodes dynamically. using reflection.
  2. If you have ever programmed for android, you must know that programmers design the view of their apps using .xml files. Even in this case, your widgets are loaded dynamically using reflection. Basic example, in android:

    <Button  ...
         android:onClick="callMe" />    
    

Then you write the callMe(View view) method in the .java file. This listener is added to the button using reflection.

  1. Frameworks like Spring, Hibernate, etc also use reflection for their processing.

So there are both pros and cons of reflection.

You might want to refer this for further information

Upvotes: 1

Related Questions