StaticFieldNameAdapter.java

  1. package org.opentrafficsim.xml.bindings;

  2. import java.lang.reflect.Field;

  3. import org.djutils.logger.CategoryLogger;
  4. import org.djutils.reflection.ClassUtil;
  5. import org.opentrafficsim.xml.bindings.types.FieldType;

  6. /**
  7.  * StaticFieldNameAdapter converts between the XML String for a class name and the Class object. <br>
  8.  * <p>
  9.  * Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
  10.  * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
  11.  * </p>
  12.  * @author <a href="https://github.com/averbraeck">Alexander Verbraeck</a>
  13.  * @author <a href="https://tudelft.nl/staff/p.knoppers-1">Peter Knoppers</a>
  14.  * @author <a href="https://github.com/wjschakel">Wouter Schakel</a>
  15.  */
  16. public class StaticFieldNameAdapter extends ExpressionAdapter<Field, FieldType>
  17. {

  18.     /** {@inheritDoc} */
  19.     @Override
  20.     public FieldType unmarshal(final String field)
  21.     {
  22.         if (isExpression(field))
  23.         {
  24.             return new FieldType(trimBrackets(field));
  25.         }
  26.         try
  27.         {
  28.             int dot = field.lastIndexOf(".");
  29.             String className = field.substring(0, dot);
  30.             String fieldName = field.substring(dot + 1);
  31.             return new FieldType(ClassUtil.resolveField(Class.forName(className), fieldName));
  32.         }
  33.         catch (Exception exception)
  34.         {
  35.             CategoryLogger.always().error(exception, "Problem parsing Static Field '" + field + "'");
  36.             throw new RuntimeException(exception);
  37.         }
  38.     }

  39.     /** {@inheritDoc} */
  40.     @Override
  41.     public String marshal(final FieldType value)
  42.     {
  43.         return marshal(value, (v) -> (v.getDeclaringClass().getName() + "." + v.getName()));
  44.     }

  45. }