ConvertAction

来源:互联网 发布:c语言buffer 编辑:程序博客网 时间:2024/05/19 17:24
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.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.ISelectionService;
import org.eclipse.ui.internal.Workbench;


import com.test.myplugin.ConvertStore;


public class ConvertAction extends AbstractHandler{


@Override
public Object execute(ExecutionEvent arg0) throws ExecutionException {
@SuppressWarnings("restriction")
ISelectionService selectionService =     
                Workbench.getInstance().getActiveWorkbenchWindow().getSelectionService();    
        ISelection selection = selectionService.getSelection();  
        
        Object [] compUnits = ((IStructuredSelection) selection).toArray();
        
        IType fromType = ConvertStore.getValue("from");
        IType toType =  ConvertStore.getValue("to");
        ICompilationUnit compUnit = (ICompilationUnit) compUnits[0];


        IType convert = compUnit.findPrimaryType();
        
        try {
        if(convert != null && convert.isClass()){
        String con = generateConvert(fromType, toType);
    convert.createMethod(con, null, false, null);
        }
} catch (Exception e) {
e.printStackTrace();
}
        return null;
}

public String generateConvert(IType fromType, IType toType){
String fromClassName = fromType.getElementName();
String toClassName = toType.getElementName();
StringBuffer sbf = new StringBuffer("public static "+toClassName+" convert"+fromClassName+"2"+toClassName+"("+fromClassName+" "+lower(fromClassName)+"){\n");
sbf.append("\t"+toClassName+" "+lower(toClassName)+" = new "+toClassName+"();\n");
try {

IField[] fromFields = fromType.getFields();

for (IField fromField : fromFields){
sbf.append("\t"+lower(toClassName)+".set"+upper(fromField.getElementName())+"("+lower(fromClassName)+".get"+upper(fromField.getElementName())+"());\n");
}

} catch (Exception e) {
}

sbf.append("\treturn "+lower(toClassName)+";\n");
sbf.append("}");

return sbf.toString();
}

public static String upper(String str){
StringBuffer sb = new StringBuffer(str);
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
str = sb.toString();
return str;
}

public static String lower(String str){
StringBuffer sb = new StringBuffer(str);
sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));
str = sb.toString();
return str;
}
}
0 0