Solved

creating a factory using spring config files

Posted on 2014-01-21
7
198 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
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 

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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
How to get all the API from website? 11 92
split53 challenge 7 99
null output 3 25
How to convert from xls to xlsx using java 7 41
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

832 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