Solved

creating a factory using spring config files

Posted on 2014-01-21
7
205 Views
Last Modified: 2014-04-22
I have a class with has a lot of static variables and each has a value . I am trying to see if I can dynamically access the static variable based of certain condition . Is there a way i can create a factory using spring configs which would let me access a static variable dynamically .

In the example below i would like to do a A.get(""); rather than if else loop

Eg :
class A
Static String A = "###";
Static String B = "****";

Class B
if (Cond1)
A.A
else
A.B
0
Comment
Question by:FranklinRaj22
  • 3
  • 2
7 Comments
 
LVL 20

Expert Comment

by:chaitu chaitu
ID: 39799194
put the xyz value in properties and load this properties from config file.

@Value("${xyx}")
      private int xyz;
0
 

Author Comment

by:FranklinRaj22
ID: 39800295
The prob is we do not want to expose the values of xyz in config file . We would like to have it as a constants file and static varible .
0
 
LVL 35

Expert Comment

by:mccarl
ID: 39820263
Just to be clear, is the value that you want to pass to this .get() method the same as the name of the static variable in class A? eg. should A.get("A") return "###" and A.get("B") return "****" in your example above?

If not, what is the value that you pass to the get() method and how should it map to static variable names in class A?
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

Author Comment

by:FranklinRaj22
ID: 39825620
Yes @mcCarl
0
 
LVL 35

Accepted Solution

by:
mccarl earned 500 total points
ID: 39831357
Sorry for the delay. You can use reflection to do the sort of thing that you are after. This doesn't really have much to do with Spring. Check out the following Constants class...
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("unused")
public class Constants {
    
    private static final String A = "###";
    private static final String B = "*****";
    
    private static Map<String, String> constantsMap = new HashMap<String, String>();
    
    static {
        for (Field field : Constants.class.getDeclaredFields()) {
            int modifiers = field.getModifiers();
            if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers) && field.getType() == String.class) {
                try {
                    constantsMap.put(field.getName(), (String) field.get(null));
                } catch (Exception e) {}
            }
        }
    }
    
    public static String get(String name) {
        return constantsMap.get(name);
    }
}

Open in new window

You can now simply define further constants at the top of that class, and the rest of the code will just pick up those new fields and make them available via the .get() method.


And just in case it isn't clear, this is how you could use the above...
public class TestConstants {
    
    public static void main(String[] args) {
        System.out.println("A: " + Constants.get("A"));
        System.out.println("B: " + Constants.get("B"));
        System.out.println("C: " + Constants.get("C"));
    }
    
}

Open in new window

Note that in the case that there is no constant (such as "C" above) it return null. If desired, you could easily modify the Constants class to throw an exception instead if the constant name wasn't found.
0
 
LVL 35

Expert Comment

by:mccarl
ID: 40002837
Why was only a 'B' grade awarded? What was wrong with my answer?
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
reverse digits of a number using for loop 5 52
servlet filter example 37 72
maven module vs maven project 3 47
Convert from a json string array to a Java object 3 54
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

821 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question