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

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

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

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

/**
 * When a method throws a RuntimeExeception, remove it and annotate the method
 * with an Exception annotation
 */
public class RuntimeExceptionProcessor extends AbstractProcessor> {
	public void process(CtMethod m) {
		CompilationUnit cu=m.getPosition().getCompilationUnit();
		if(cu==null) return;
		if (m.getBody() == null)
			return;
		CtTypeReference serializable = getFactory().Type()
				.createReference(RuntimeException.class);
		if (m.getThrownTypes().contains(serializable)) {
			m.getThrownTypes().remove(serializable);
			SourceCodeFragment fragment = new SourceCodeFragment();
			int execNameStart = m.getPosition().getSourceStart();
			int execDeclStart = cu.beginOfLineIndex(execNameStart);
			int tabCount = cu.getTabCount(execDeclStart);
			int execDeclEnd = cu.getOriginalSourceCode().indexOf('{', execNameStart);
			fragment.position = execDeclStart;
			fragment.replacementLength = execDeclEnd - execDeclStart;
			DefaultJavaPrettyPrinter pp = new DefaultJavaPrettyPrinter(
					getEnvironment());
			pp.setTabCount(tabCount).writeTabs().write("@Exception ");
			pp.writeModifiers(m);
			pp.writeGenericsParameter(m.getFormalTypeParameters());
			pp.writeTypeReference(m.getType()).write(" ").write(m.getSimpleName());
			pp.write("(").writeExecutableParameters(m).write(")");
			pp.writeThrowsClause(m).write(" ");
			fragment.code = pp.getResult().toString();
			cu.addSourceCodeFragment(fragment);
		}
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy