All Downloads are FREE. Search and download functionalities are using the official Maven repository.

spoon.examples.fragments.processing.SerializableProcessor Maven / Gradle / Ivy

The newest version!
package spoon.examples.fragments.processing;

import java.io.Serializable;

import spoon.processing.AbstractProcessor;
import spoon.reflect.cu.CompilationUnit;
import spoon.reflect.cu.SourceCodeFragment;
import spoon.reflect.declaration.CtClass;
import spoon.reflect.reference.CtTypeReference;
import spoon.reflect.visitor.DefaultJavaPrettyPrinter;

/**
 * When a class implements a Serializable interface, remove it and annotate the
 * class with a Serializable annotation.
 */

public class SerializableProcessor extends AbstractProcessor> {
	public void process(CtClass c) {
		CompilationUnit cu=c.getPosition().getCompilationUnit();
		if(cu==null) return;
		CtTypeReference serializable = getFactory().Type()
				.createReference(Serializable.class);
		if (c.getSuperInterfaces().contains(serializable)) {
			c.getSuperInterfaces().remove(serializable);
			SourceCodeFragment fragment = new SourceCodeFragment();
			int classNameStart = c.getPosition().getSourceStart();
			int classDeclStart = cu.beginOfLineIndex(classNameStart);
			int classDeclEnd = cu.getOriginalSourceCode().indexOf('{',
					classNameStart);
			fragment.position = classDeclStart;
			fragment.replacementLength = classDeclEnd - classDeclStart;
			DefaultJavaPrettyPrinter pp = new DefaultJavaPrettyPrinter(
					getEnvironment());
			pp.writeModifiers(c).write("class " + c.getSimpleName());
			pp.writeGenericsParameter(c.getFormalTypeParameters());
			pp.writeExtendsClause(c).writeImplementsClause(c).write(" ");
			fragment.code = "@Serializable " + pp.getResult().toString();
			cu.addSourceCodeFragment(fragment);
		}
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy