/* * Copyright 2007 Wishnu Prasetya. * * This file is part of T2. * T2 is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License (GPL) as published by the * Free Software Foundation; either version 3 of the License, or any * later version. * * T2 is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * A copy of the GNU General Public License can be found in T2 distribution. * If it is missing, see http://www.gnu.org/licenses. */ package Sequenic.T2.Seq; import java.io.IOException; import java.io.NotSerializableException; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.util.Collection; import Sequenic.P2.StringFormater; import Sequenic.T2.Pool; import Sequenic.T2.Msg.T2Error; /** * A MkVal step where a collection like object is constructed. Set * collectionType to "ARRAY" to create an array, and else the name * of the class implementing Collection to make a collection. */ public class CREATE_COLLECTION_LIKE extends MkValStep { private static final long serialVersionUID = 1L; public String collectionType; public Class elementType; public int size; public MkValStep[] elements; public CREATE_COLLECTION_LIKE(String Ctype, Class ElemTy, int n, MkValStep[] elems) { collectionType = Ctype; elementType = ElemTy; size = n; elements = elems; } public Object exec(Class CUT, Pool pool) throws InvocationTargetException { Object result = null; try { if (collectionType.equals(MkValStep.ARRAY)) { result = Array.newInstance(elementType, size); for (int i = 0; i < size; i++) { Array.set(result, i, elements[i].exec(CUT,pool)); } return result; } // ELSE: result = (Collection) Class.forName(collectionType).newInstance(); for (int i = 0; i < size; i++) { ((Collection) result).add(elements[i].exec(CUT,pool)); } } catch (InvocationTargetException e) { throw e; } catch (Exception e) { throw new T2Error("Fail to create a collection " + this, e); } return result; } @Override public String toString() { String result = "CREATE_COLLECTION_LIKE of type " + collectionType + ": "; String elemsTxt = ""; for (int i = 0; i < elements.length; i++) { elemsTxt = elemsTxt + elements[i]; if (i < elements.length - 1) { elemsTxt = elemsTxt + ",\n"; } } result = result + "[ " + StringFormater.indentButFirst(elemsTxt, 4) + " ]"; return result; } @Override public boolean isObsolete() { return false; } private void writeObject(java.io.ObjectOutputStream out) throws IOException { throw new NotSerializableException(); } }