use of com.laytonsmith.core.constructs.CByteArray in project CommandHelper by EngineHub.
the class Static method getJavaObject.
/**
* Given a MethodScript object, returns a java object.
*
* @param construct
* @return
*/
public static Object getJavaObject(Construct construct) {
if ((construct == null) || (construct instanceof CNull)) {
return null;
} else if (construct instanceof CVoid) {
return "";
} else if (construct instanceof CBoolean) {
return ((CBoolean) construct).getBoolean();
} else if (construct instanceof CInt) {
return ((CInt) construct).getInt();
} else if (construct instanceof CDouble) {
return ((CDouble) construct).getDouble();
} else if (construct instanceof CString) {
return construct.val();
} else if (construct instanceof CByteArray) {
return ((CByteArray) construct).asByteArrayCopy();
} else if (construct instanceof CResource) {
return ((CResource) construct).getResource();
} else if (construct instanceof CArray) {
CArray array = (CArray) construct;
if (array.isAssociative()) {
HashMap<String, Object> map = new HashMap<>();
for (Construct key : array.keySet()) {
Construct c = array.get(key.val(), Target.UNKNOWN);
map.put(key.val(), (c == array) ? map : getJavaObject(c));
}
return map;
} else {
Object[] a = new Object[(int) array.size()];
boolean nullable = false;
Class<?> clazz = null;
for (int i = 0; i < array.size(); i++) {
Construct c = array.get(i, Target.UNKNOWN);
if (c == array) {
a[i] = a;
} else {
a[i] = getJavaObject(array.get(i, Target.UNKNOWN));
}
if (a[i] != null) {
if (clazz == null) {
clazz = a[i].getClass();
} else if (!clazz.equals(Object.class)) {
// to test if it is possible to return something more specific than Object[]
Class<?> cl = a[i].getClass();
while (!clazz.isAssignableFrom(cl)) {
clazz = clazz.getSuperclass();
}
}
} else {
nullable = true;
}
}
if ((clazz != null) && (!clazz.equals(Object.class))) {
if (clazz.equals(Boolean.class) && !nullable) {
boolean[] r = new boolean[a.length];
for (int i = 0; i < a.length; i++) {
r[i] = (boolean) a[i];
}
return r;
}
if (clazz.equals(Long.class) && !nullable) {
long[] r = new long[a.length];
for (int i = 0; i < a.length; i++) {
r[i] = (long) a[i];
}
return r;
} else if (clazz.equals(Double.class) && !nullable) {
double[] r = new double[a.length];
for (int i = 0; i < a.length; i++) {
r[i] = (double) a[i];
}
return r;
} else {
Object[] r = (Object[]) Array.newInstance(clazz, a.length);
System.arraycopy(a, 0, r, 0, a.length);
return r;
}
} else {
return a;
}
}
} else {
return construct;
}
}
Aggregations