SampleAction

来源:互联网 发布:c语言buffer 编辑:程序博客网 时间:2024/06/05 21:04
package com.test.myplugin.handlers;


import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.ISelectionService;
import org.eclipse.ui.internal.Workbench;


/**
 * Our sample handler extends AbstractHandler, an IHandler base class.
 * @see org.eclipse.core.commands.IHandler
 * @see org.eclipse.core.commands.AbstractHandler
 */
public class SampleAction extends AbstractHandler {
/**
* The constructor.
*/
public SampleAction() {
}


/**
* the command has been executed, so extract extract the needed information
* from the application context.
*/
public Object execute(ExecutionEvent event) throws ExecutionException {

ISelectionService selectionService =     
                Workbench.getInstance().getActiveWorkbenchWindow().getSelectionService();    
        ISelection selection = selectionService.getSelection();  
        
        Object [] compUnits = ((IStructuredSelection) selection).toArray();
        
        for (int i = 0; i < compUnits.length; i++){
        ICompilationUnit compUnit = (ICompilationUnit) compUnits[i];


            IType type = compUnit.findPrimaryType();
            
            try {
            // 拼接toString内容
if(type != null && type.isClass()){
String toString = generateToString(type);
type.createMethod(toString, null, false, null);
}
} catch (JavaModelException e) {
e.printStackTrace();
}
        }
return null;
}

public String generateToString(IType type){
StringBuffer sbf = new StringBuffer("public String toString(){\n");
sbf.append("\tStringBuffer sbf = new StringBuffer();\n");
try {
IField[] fields = type.getFields();
String className = type.getElementName();

sbf.append("\n");
sbf.append("\tsbf.append(\""+className+"=[\");\n");
for (IField field : fields){
if (!"serialVersionUID".equals(field.getElementName())){
sbf.append("\tsbf.append(\""+field.getElementName()+"=\").append("+field.getElementName()+").append(\",\");\n");
}
}
sbf.append("\tsbf.append(\"super.toString=\").append(super.toString()).append(\"]\");\n");
sbf.append("\n");
sbf.append("\treturn sbf.toString();\n");
} catch (Exception e) {
}
sbf.append("}");
return sbf.toString();
}
}
0 0
原创粉丝点击