* Construct scalar instance when the runtime class is known. Recursive
* structures are not supported.
*/
protected class ConstructScalar extends AbstractConstruct {
public Object construct(Node nnode) {
ScalarNode node = (ScalarNode) nnode;
Class<?> type = node.getType();
Object result;
if (type.isPrimitive() || type == String.class || Number.class.isAssignableFrom(type)
|| type == Boolean.class || Date.class.isAssignableFrom(type)
|| type == Character.class || type == BigInteger.class
|| type == BigDecimal.class || Enum.class.isAssignableFrom(type)
|| Tag.BINARY.equals(node.getTag()) || Calendar.class.isAssignableFrom(type)) {
// standard classes created directly
result = constructStandardJavaInstance(type, node);
} else {
// there must be only 1 constructor with 1 argument
java.lang.reflect.Constructor<?>[] javaConstructors = type.getConstructors();
int oneArgCount = 0;
java.lang.reflect.Constructor<?> javaConstructor = null;
for (java.lang.reflect.Constructor<?> c : javaConstructors) {
if (c.getParameterTypes().length == 1) {
oneArgCount++;
javaConstructor = c;
}
}
Object argument;
if (javaConstructor == null) {
throw new YAMLException("No single argument constructor found for " + type);
} else if (oneArgCount == 1) {
argument = constructStandardJavaInstance(
javaConstructor.getParameterTypes()[0], node);
} else {
// TODO it should be possible to use implicit types instead
// of forcing String. Resolver must be available here to
// obtain the implicit tag. Then we can set the tag and call
// callConstructor(node) to create the argument instance.
// On the other hand it may be safer to require a custom
// constructor to avoid guessing the argument class
argument = constructScalar(node);
try {
javaConstructor = type.getConstructor(String.class);
} catch (Exception e) {
throw new YAMLException("Can't construct a java object for scalar "
+ node.getTag() + "; No String constructor found. Exception="
+ e.getMessage(), e);
}
}
try {
result = javaConstructor.newInstance(argument);
} catch (Exception e) {
throw new ConstructorException(null, null,
"Can't construct a java object for scalar " + node.getTag()
+ "; exception=" + e.getMessage(), node.getStartMark(), e);
}
}
return result;
}