1

There is my actual solution to add a value to a hashmap

private HashMap<String,Sexpr> contexte = new HashMap<String,Sexpr>();

...

this.putVariable("car",Car.CAR);
this.putVariable("cdr",Cdr.CDR);

I want to do the same thing from a XML by using SAX

<root>
    <!-- Les types prédéfinis -->
      <type symbole="car" type="expr" class="Car.CAR"/>
      <type symbole="cdr" type="expr" class="Cdr.CDR"/>    
</root>

I can get theses values from my handler (with Sax) by using attributes.getValue(i).toString(), i'd like to convert my string to Java Code for the second part of my request to access my class Car or Cdr in this example

X.putVariable(attributes.getValue(0).toString, attributes.getValue(2).? );

Thank you for your help

  • I suggest changing the subject of this question to indicate you want to map a string to a java object. – hcpl Mar 29 '12 at 16:08

2 Answers2

0

So what I understand is that you want to map the "Car.CAR" string to the Car.CAR java class member.

What is the Member like? Is the member really needed? Since you just have it with the same name as the class and it seems to be a constant (based on the java convention for capitals) I suspect not.

If you just want to store a class reference then you could go for the Class.forName(String cls):Class method. That class object can be stored in the HashMap. Example:

Class cls = Class.forName("Car");

Also check this similar question if that is what you want: java String to class

Community
  • 1
  • 1
hcpl
  • 17,382
  • 7
  • 72
  • 73
0

It looks like you will have to use reflection to retrieve the static member (called a Field in the Java reflection APIs) named in the "class" attribute. For example (untested):

public static Object lookupStaticMember(String name) /* throws many */ {
  String classField[] = name.split("\\.");
  Class<?> klass = Class.forName(classField[0]);
  Field field = klass.getField(classField[1]);
  int mods = field.getModifiers();
  if ((Modifier.PUBLIC & mods == 0) || (Modifier.STATIC & mods == 0)) {
    throw new IllegalArgumentException("field " + name + " is not public static");
  }
  return field.get(klass);
}

Now you can use it as:

X.putVariable(attributes.getValue(0).toString(),
    (Sexpr) lookupStaticMember(attributes.getValue(2).toString()));
maerics
  • 151,642
  • 46
  • 269
  • 291