Solved

creating a factory using spring config files

Posted on 2014-01-21
7
192 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…

937 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now