package jfun.yan.xml.nuts;
import java.lang.reflect.Array;
import jfun.util.Misc;
import jfun.util.StringUtils;
import jfun.yan.Component;
import jfun.yan.Components;
import jfun.yan.SimpleComponent;
import jfun.yan.util.ReflectionUtil;
/**
* Nut class for <array> tag.
* <p>
* @author Ben Yu
* Nov 9, 2005 11:39:29 PM
*/
public class ArrayNut extends CollectionNut {
private void checkTypeMatch(Class expected, Class actual){
if(!ReflectionUtil.isAssignableFrom(expected, actual)){
throw raise(Misc.getTypeName(actual)
+ " is not subtype of "+Misc.getTypeName(expected));
}
}
public void setType(Class type){
if(!type.isArray()){
raise(Misc.getTypeName(type)+" is not an array.");
}
final Class etype = type.getComponentType();
final Class of = getOf();
if(of==null){
super.setOf(etype);
}
else{
checkTypeMatch(etype, of);
}
super.setType(type);
}
public void setOf(Class oftype){
final Class of = getOf();
if(of==null){
super.setType(Misc.getArrayType(oftype));
}
else{
checkTypeMatch(of, oftype);
}
super.setOf(oftype);
}
/*
private Component convert(final int ind, final Class elem_type, Component c){
return c.map(new Map(){
public Object map(Object obj){
return convert(elem_type, obj);
}
});
}
private Component[] convert(final Class elem_type, Component[] ccs){
if(String.class.equals(elem_type)){
return ccs;
}
else{
final Component[] ret = new Component[ccs.length];
for(int i=0; i<ret.length; i++){
ret[i] = convert(i, elem_type, ccs[i]);
}
return ret;
}
}*/
public Component eval(){
final Component[] elements = getMandatoryElements();
final Class type = getType(Object[].class);
final Class oftype = getOf();
final Class etype = oftype==null?Object.class:oftype;
final Component step1 = new SimpleComponent(type){
public Object create(){
return Array.newInstance(etype, elements.length);
}
public String toString(){
return StringUtils.listArray("[",",","]",elements);
}
};
return Components.storeArray(step1, elements);
/*
if(elem_type!=null){
return Components.array(convert(elem_type, elements), elem_type);
}
else{
return Components.array(elements);
}*/
}
}