/*
* Copyright (C) 2001 Mika Riekkinen, Joni Suominen
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package alt.jiapi.instrumentor;
import java.lang.reflect.Modifier;
import org.apache.log4j.Category;
import alt.jiapi.Runtime;
import alt.jiapi.reflect.FieldExistsException;
import alt.jiapi.reflect.InstructionList;
import alt.jiapi.reflect.JiapiClass;
import alt.jiapi.reflect.JiapiField;
/**
* A ClassInstrumentor which creates a new field for a class.
*
* @author Mika Riekkinen
* @author Joni Suominen
* @version $Revision: 1.7 $ $Date: 2004/03/15 14:47:53 $
*/
public class CreateFieldInstrumentor extends AbstractInstrumentor {
private static Category log = Runtime.getLogCategory(CreateFieldInstrumentor.class);
private int modifiers;
private String type;
private String name;
/**
* Constructor.
* @param modifiers Modifiers of the Field to be created
* @param type Type of the field to be created
* @param name Name of the field to be created
*/
public CreateFieldInstrumentor(int modifiers, String type, String name) {
this.modifiers = modifiers;
this.type = type;
this.name = name;
}
/**
* Constructs CreateFieldInstrumentor with existing JiapiField.
* @param field JiapiField, that is used to get relevant information
*/
public CreateFieldInstrumentor(JiapiField field) {
this(field.getModifiers(), field.getTypeName(), field.getName());
}
/**
* Instrument a JiapiClass.
*
* @param clazz A Class to be instrumented
*/
public void instrument(InstructionList il) {
JiapiClass clazz = getCurrentClass();
log.info("Adding field '" + modifiers + " " + type + " " + name +
"' to " + clazz.getName());
// If the class is interface, then the modifiers must be public,
// static and final.
if (Modifier.isInterface(clazz.getModifiers())) {
if (!(Modifier.isPublic(modifiers) &&
Modifier.isStatic(modifiers) &&
Modifier.isFinal(modifiers))) {
log.info("Cannot add '" + modifiers + " " + type + " " + name +
"' to " + clazz.getName());
forward(il);
return;
}
}
try {
clazz.addField(modifiers, type, name);
}
catch (FieldExistsException fee) {
log.info("field " + fee.getField() + " already exists in a class "+
clazz.getName());
}
forward(il);
}
}