View Javadoc
1   package org.opentrafficsim.xml.bindings;
2   
3   import java.lang.reflect.Field;
4   
5   import org.djutils.logger.CategoryLogger;
6   import org.djutils.reflection.ClassUtil;
7   import org.opentrafficsim.xml.bindings.types.FieldType;
8   
9   /**
10   * StaticFieldNameAdapter converts between the XML String for a class name and the Class object. <br>
11   * <p>
12   * Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
13   * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
14   * </p>
15   * @author <a href="https://github.com/averbraeck">Alexander Verbraeck</a>
16   * @author <a href="https://tudelft.nl/staff/p.knoppers-1">Peter Knoppers</a>
17   * @author <a href="https://github.com/wjschakel">Wouter Schakel</a>
18   */
19  public class StaticFieldNameAdapter extends ExpressionAdapter<Field, FieldType>
20  {
21  
22      /** {@inheritDoc} */
23      @Override
24      public FieldType unmarshal(final String field)
25      {
26          if (isExpression(field))
27          {
28              return new FieldType(trimBrackets(field));
29          }
30          try
31          {
32              int dot = field.lastIndexOf(".");
33              String className = field.substring(0, dot);
34              String fieldName = field.substring(dot + 1);
35              return new FieldType(ClassUtil.resolveField(Class.forName(className), fieldName));
36          }
37          catch (Exception exception)
38          {
39              CategoryLogger.always().error(exception, "Problem parsing Static Field '" + field + "'");
40              throw new RuntimeException(exception);
41          }
42      }
43  
44      /** {@inheritDoc} */
45      @Override
46      public String marshal(final FieldType value)
47      {
48          return marshal(value, (v) -> (v.getDeclaringClass().getName() + "." + v.getName()));
49      }
50  
51  }