What is Java Reflection and PropertiesIn this article I will be explaining how you load classes dynamically using a properties file and Java Reflections. The Properties file are basically a collection of key-value pairs. It is the most commonly used mechanism for storing [url=]applications[/url] configuration data and settings. Reflection is a feature available in Java used by developers for [url=]examining[/url] and modifying the run-time behavior of applications running in the JVM.MyBirds exampleLet us start with a very simple problem statement: I should be able to load characters of a particular bird when I specify it's name. For e.g: When i specify duck, the [url=]calling[/url] the sound() function should [url=]print[/url] "quack";This is a situation where you need to load a class dynamically based on some data provided by the client or external source. You also want the flexibility to configure classes in a simple properties file and these classes are having similar behavior.To implement this we will need the following components:mybirds.properties - The properties file where you can map keys to your classMyBird.java - An interface which all the classes specified in the properties file will have to implement.Duck.java, Eagle.java - The classes that implements the interface MyBird.MyBirdFactory.java - The factory class that dynamically creates classes
Let us look at the [url=]code[/url] for each of these. Let us start with mybirds.properties.[backcolor=white !important][size=1em][backcolor=rgb(212, 208, 200) !important][color=#a0a0a0 !important][size=1em]?
[backcolor=white !important][size=1em]1
[backcolor=white !important][size=1em]2
[backcolor=white !important][size=1em]3
Make sure that the value of MY_BIRDS_CONFIGURATION is same as the name of the properties file.
We can write TestCode.java to test the code.
package com.foo;
/**
* http://www.janeve.me
*/
public class TestCode {
public static void main(String[] args) {
if(args.length java -classpath ./ com.foo.TestCode duck duck eagle duck eagle eagle
The sound of the bird duck is Quack
The sound of the bird duck is Quack
The sound of the bird eagle is Scream
The sound of the bird duck is Quack
The sound of the bird eagle is Scream
The sound of the bird eagle is Scream
C:\Janeve\MyBirds>
As you can see, the classes were loaded as per your input.You may download the complete source code.
Try adding your favorite bird in the properties file and let me know how it went.