Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Reflection API  RSS feed

 
Sachin Ramesh Vir
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where the Reflection API will be useful. Give one real-time example for using reflection API.

First correct me whether I have understood the reflection API.
Reflection API is used to find out the class name, class modifiers, constructors, what inferface the class is implementing, what classes it extends and more...but finding these all at the RUNTIME.

What will be the use of finding those things at runtime?
 
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Give one real-time example for using reflection API.
Javabeans.
 
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What will be the use of finding those things at runtime?
Finding these things at runtime allows the Java program to look at itself and its environment and change both accordingly and dynamically. For example, say you've written a visual GUI builder and you want to determine if a component has a setColor() method, and if so, call that method. Reflection allows exactly that.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It also allows you to configure your program to use specific classes at runtime. For example, JDBC (Java Database Connectivity) requires a driver class that knows how to access a database. Each database (such as Oracle, Microsoft SQL Server, Microsoft Access) has its own driver class associated with it. One way to configure a program that uses a database is to put the name of the JDBC driver class in a config file. The program then reads the class name from the file and uses the Reflection API to load it. Using the scheme, you can change the underlying database fairly easily by simply editing the config file. Such a change does not require you to recompile the program.

For more information on the Reflection API, you should check out this tutorial.

Layne
 
Rick O'Shay
Ranch Hand
Posts: 531
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I will pass your method an object. I want you to call every method with the prefix "test". Reflection will let you do that.

I will pass you an object and in the GUI I want you to display all of the properties and whether they are read-only or read-write. A property is a method starting with the prefix "get". We will assume it is read-only if there is no corresponding "set" method. Reflection will allow you do do that.
[ September 23, 2005: Message edited by: Rick O'Shay ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!