Solved

creating a factory using spring config files

Posted on 2014-01-21
7
217 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 36

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
What Is Transaction Monitoring and who needs it?

Synthetic Transaction Monitoring that you need for the day to day, which ensures your business website keeps running optimally, and that there is no downtime to impact your customer experience.

 

Author Comment

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

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 36

Expert Comment

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

Featured Post

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

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

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

705 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