Eclipse get/set方法自動加上欄位註釋
阿新 • • 發佈:2018-12-14
編碼的時候通常要用到 JavaBean ,而在我們經常把註釋寫在欄位上面,但生成的Get/Set方法不會生成,通過修改Eclipse原始碼可解決,直接上例子:
/** * 員工ID */ private String userid; /** * 獲取員工ID * @return userid 員工ID */ public String getUserid() { return userid; } /** * 設定員工ID * @param userid 員工ID */ public void setUserid(String userid) { this.userid = userid; }
關閉eclipse 找到Eclipse中Jar包:org.eclipse.jdt.ui_*.jar,進行備份 找到org.eclipse.jdt.internal.corext.codemanipulation.GetterSetterUtil.class 直接用附件中的class檔案進行替換,重啟Eclipse 設定註釋風格: Window->Preferences->Java->CodeStyle->Code Templates->Comments->Getters/Setters Getters: /**
- 獲取${bare_field_name}
- @return ${bare_field_name} ${bare_field_name}
/
Setters:
/
- 設定${bare_field_name}
- @param ${bare_field_name} ${bare_field_name} */ 注意:生成Get/Set方法時勾選上Generate method comments OK,成功。
在eclipse4.2上測試通過。
替換GetterSetterUtil.class的原碼:
package org.eclipse.jdt.internal.corext.codemanipulation;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.*;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.JdtFlags;
import org.eclipse.jdt.ui.CodeGeneration;
/**
* @author [email protected]
*/
public class GetterSetterUtil {
private static final String EMPTY[] = new String[0];
private GetterSetterUtil() {
}
public static String getGetterName(IField field, String excludedNames[])
throws JavaModelException {
boolean useIs = StubUtility.useIsForBooleanGetters(field
.getJavaProject());
return getGetterName(field, excludedNames, useIs);
}
private static String getGetterName(IField field, String excludedNames[],
boolean useIsForBoolGetters) throws JavaModelException {
if (excludedNames == null)
excludedNames = EMPTY;
return getGetterName(field.getJavaProject(), field.getElementName(),
field.getFlags(), useIsForBoolGetters
&& JavaModelUtil.isBoolean(field), excludedNames);
}
public static String getGetterName(IVariableBinding variableType,
IJavaProject project, String excludedNames[], boolean isBoolean) {
boolean useIs = StubUtility.useIsForBooleanGetters(project)
&& isBoolean;
return getGetterName(project, variableType.getName(), variableType
.getModifiers(), useIs, excludedNames);
}
public static String getGetterName(IJavaProject project, String fieldName,
int flags, boolean isBoolean, String excludedNames[]) {
return NamingConventions.suggestGetterName(project, fieldName, flags,
isBoolean, excludedNames);
}
public static String getSetterName(IVariableBinding variableType,
IJavaProject project, String excludedNames[], boolean isBoolean) {
return getSetterName(project, variableType.getName(), variableType
.getModifiers(), isBoolean, excludedNames);
}
public static String getSetterName(IJavaProject project, String fieldName,
int flags, boolean isBoolean, String excludedNames[]) {
return NamingConventions.suggestSetterName(project, fieldName, flags,
isBoolean, excludedNames);
}
public static String getSetterName(IField field, String excludedNames[])
throws JavaModelException {
if (excludedNames == null)
excludedNames = EMPTY;
return NamingConventions.suggestSetterName(field.getJavaProject(),
field.getElementName(), field.getFlags(), JavaModelUtil
.isBoolean(field), excludedNames);
}
public static IMethod getGetter(IField field) throws JavaModelException {
String getterName = getGetterName(field, EMPTY, true);
IMethod primaryCandidate = JavaModelUtil.findMethod(getterName,
new String[0], false, field.getDeclaringType());
if (!JavaModelUtil.isBoolean(field) || primaryCandidate != null
&& primaryCandidate.exists()) {
return primaryCandidate;
} else {
String secondCandidateName = getGetterName(field, EMPTY, false);
return JavaModelUtil.findMethod(secondCandidateName, new String[0],
false, field.getDeclaringType());
}
}
public static IMethod getSetter(IField field) throws JavaModelException {
String args[] = { field.getTypeSignature() };
return JavaModelUtil.findMethod(getSetterName(field, EMPTY), args,
false, field.getDeclaringType());
}
/**
* Set方法註釋
* @param field
* @param setterName
* @param addComments
* @param flags
* @return
* @throws CoreException
*/
public static String getSetterStub(IField field, String setterName,
boolean addComments, int flags) throws CoreException {
String fieldName = field.getElementName();
IType parentType = field.getDeclaringType();
String returnSig = field.getTypeSignature();
String typeName = Signature.toString(returnSig);
IJavaProject project = field.getJavaProject();
String accessorName = NamingConventions.removePrefixAndSuffixForFieldName(project, fieldName, field.getFlags());
String argname = StubUtility.suggestArgumentName(project, accessorName,EMPTY);
boolean isStatic = Flags.isStatic(flags);
boolean isSync = Flags.isSynchronized(flags);
boolean isFinal = Flags.isFinal(flags);
String lineDelim = "\n";
StringBuffer buf = new StringBuffer();
if (addComments) {
String comment = CodeGeneration.getSetterComment(
field.getCompilationUnit(),
parentType.getTypeQualifiedName('.'),
setterName,
field.getElementName(),
typeName,
argname,
accessorName,
lineDelim);
ISourceRange sr = field.getJavadocRange();
if (null != sr) {
String filedComment = field.getSource();
filedComment = filedComment.substring(0, sr.getLength());
filedComment = filedComment.replaceAll("[\n,\r,*,/, ,\t]", "");
comment = comment.replaceFirst(field.getElementName(), filedComment);
int i = comment.lastIndexOf(field.getElementName());
int j = getCount(comment, field.getElementName());
if (i != -1 && j >= 2) {
comment = comment.substring(0, i) + filedComment + comment.substring(i + field.getElementName().length());
}
}
if (comment != null) {
buf.append(comment);
buf.append(lineDelim);
}
}
buf.append(JdtFlags.getVisibilityString(flags));
buf.append(' ');
if (isStatic)
buf.append("static ");
if (isSync)
buf.append("synchronized ");
if (isFinal)
buf.append("final ");
buf.append("void ");
buf.append(setterName);
buf.append('(');
buf.append(typeName);
buf.append(' ');
buf.append(argname);
buf.append(") {");
buf.append(lineDelim);
boolean useThis = StubUtility.useThisForFieldAccess(project);
if (argname.equals(fieldName) || useThis && !isStatic)
if (isStatic)
fieldName = parentType.getElementName() + '.' + fieldName;
else
fieldName = "this." + fieldName;
String body = CodeGeneration.getSetterMethodBodyContent(field
.getCompilationUnit(), parentType.getTypeQualifiedName('.'),
setterName, fieldName, argname, lineDelim);
if (body != null)
buf.append(body);
buf.append("}");
buf.append(lineDelim);
return buf.toString();
}
/**
* Get方法註釋
* @param field
* @param getterName
* @param addComments
* @param flags
* @return
* @throws CoreException
*/
public static String getGetterStub(IField field, String getterName,
boolean addComments, int flags) throws CoreException {
String fieldName = field.getElementName();
IType parentType = field.getDeclaringType();
boolean isStatic = Flags.isStatic(flags);
boolean isSync = Flags.isSynchronized(flags);
boolean isFinal = Flags.isFinal(flags);
String typeName = Signature.toString(field.getTypeSignature());
String accessorName = NamingConventions.removePrefixAndSuffixForFieldName(field.getJavaProject(), fieldName, field.getFlags());
String lineDelim = "\n";
StringBuffer buf = new StringBuffer();
if (addComments) {
//field.getCompilationUnit() 得到當前類檔案內容,就是要get,set的東西
//parentType.getTypeQualifiedName('.') 得到類名
//getterName 拼出get的方法名
//field.getElementName() 得到欄位名
//typeName 型別
String comment= CodeGeneration.getGetterComment(
field.getCompilationUnit(),
parentType.getTypeQualifiedName('.'),
getterName,
field.getElementName(),
typeName,
accessorName,
lineDelim);
ISourceRange sr = field.getJavadocRange();
if( null != sr ) {
String filedComment = field.getSource();
filedComment = filedComment.substring(0, sr.getLength());
filedComment = filedComment.replaceAll("[\n,\r,*,/, ,\t]", "");
comment = comment.replaceFirst(field.getElementName(), filedComment);
int i = comment.lastIndexOf(field.getElementName());
int j = getCount(comment, field.getElementName());
if (i != -1 && j >= 2) {
comment = comment.substring(0, i) + filedComment + comment.substring(i + field.getElementName().length());
}
}
if (comment != null) {
buf.append(comment);
buf.append(lineDelim);
}
}
buf.append(JdtFlags.getVisibilityString(flags));
buf.append(' ');
if (isStatic)
buf.append("static ");
if (isSync)
buf.append("synchronized ");
if (isFinal)
buf.append("final ");
buf.append(typeName);
buf.append(' ');
buf.append(getterName);
buf.append("() {");
buf.append(lineDelim);
boolean useThis = StubUtility.useThisForFieldAccess(field.getJavaProject());
if (useThis && !isStatic)
fieldName = "this." + fieldName;
String body = CodeGeneration.getGetterMethodBodyContent(field.getCompilationUnit(), parentType.getTypeQualifiedName('.'), getterName, fieldName, lineDelim);
if (body != null)
buf.append(body);
buf.append("}");
buf.append(lineDelim);
return buf.toString();
}
private static int getCount(String str, String sign) {
// 查詢某一字串中str,特定子串sign的出現次數
if (str == null)
return 0;
double i = str.length();
str = str.replaceAll(sign, "");// 將串中的字元sign替換成""
return (int) (i - str.length()) / sign.length();
}
public static Expression getAssignedValue(ASTNode node,
ASTRewrite astRewrite, Expression getterExpression,
ITypeBinding variableType, boolean is50OrHigher) {
org.eclipse.jdt.core.dom.InfixExpression.Operator op = null;
AST ast = astRewrite.getAST();
if (isNotInBlock(node))
return null;
if (node.getNodeType() == 7) {
Assignment assignment = (Assignment) node;
Expression rightHandSide = assignment.getRightHandSide();
Expression copiedRightOp = (Expression) astRewrite
.createCopyTarget(rightHandSide);
if (assignment.getOperator() == org.eclipse.jdt.core.dom.Assignment.Operator.ASSIGN) {
ITypeBinding rightHandSideType = rightHandSide
.resolveTypeBinding();
copiedRightOp = createNarrowCastIfNessecary(copiedRightOp,
rightHandSideType, ast, variableType, is50OrHigher);
return copiedRightOp;
}
if (getterExpression != null) {
InfixExpression infix = ast.newInfixExpression();
infix.setLeftOperand(getterExpression);
infix.setOperator(ASTNodes.convertToInfixOperator(assignment
.getOperator()));
infix.setRightOperand(copiedRightOp);
ITypeBinding infixType = infix.resolveTypeBinding();
return createNarrowCastIfNessecary(infix, infixType, ast,
variableType, is50OrHigher);
}
} else if (node.getNodeType() == 37) {
PostfixExpression po = (PostfixExpression) node;
if (po.getOperator() == org.eclipse.jdt.core.dom.PostfixExpression.Operator.INCREMENT)
op = org.eclipse.jdt.core.dom.InfixExpression.Operator.PLUS;
if (po.getOperator() == org.eclipse.jdt.core.dom.PostfixExpression.Operator.DECREMENT)
op = org.eclipse.jdt.core.dom.InfixExpression.Operator.MINUS;
} else if (node.getNodeType() == 38) {
PrefixExpression pe = (PrefixExpression) node;
if (pe.getOperator() == org.eclipse.jdt.core.dom.PrefixExpression.Operator.INCREMENT)
op = org.eclipse.jdt.core.dom.InfixExpression.Operator.PLUS;
if (pe.getOperator() == org.eclipse.jdt.core.dom.PrefixExpression.Operator.DECREMENT)
op = org.eclipse.jdt.core.dom.InfixExpression.Operator.MINUS;
}
if (op != null && getterExpression != null)
return createInfixInvocationFromPostPrefixExpression(op,
getterExpression, ast, variableType, is50OrHigher);
else
return null;
}
private static boolean isNotInBlock(ASTNode parent) {
ASTNode statement = parent.getParent();
boolean isStatement = statement.getNodeType() != 21;
ASTNode block = statement.getParent();
boolean isBlock = block.getNodeType() == 8 || block.getNodeType() == 50;
boolean isControlStatemenBody = ASTNodes
.isControlStatementBody(statement.getLocationInParent());
return isStatement || !isBlock && !isControlStatemenBody;
}
private static Expression createInfixInvocationFromPostPrefixExpression(
org.eclipse.jdt.core.dom.InfixExpression.Operator operator,
Expression getterExpression, AST ast, ITypeBinding variableType,
boolean is50OrHigher) {
InfixExpression infix = ast.newInfixExpression();
infix.setLeftOperand(getterExpression);
infix.setOperator(operator);
NumberLiteral number = ast.newNumberLiteral();
number.setToken("1");
infix.setRightOperand(number);
ITypeBinding infixType = infix.resolveTypeBinding();
return createNarrowCastIfNessecary(infix, infixType, ast, variableType,
is50OrHigher);
}
private static Expression createNarrowCastIfNessecary(
Expression expression, ITypeBinding expressionType, AST ast,
ITypeBinding variableType, boolean is50OrHigher) {
PrimitiveType castTo = null;
if (variableType.isEqualTo(expressionType))
return expression;
if (is50OrHigher) {
if (ast.resolveWellKnownType("java.lang.Character").isEqualTo(
variableType))
castTo = ast.newPrimitiveType(PrimitiveType.CHAR);
if (ast.resolveWellKnownType("java.lang.Byte").isEqualTo(
variableType))
castTo = ast.newPrimitiveType(PrimitiveType.BYTE);
if (ast.resolveWellKnownType("java.lang.Short").isEqualTo(
variableType))
castTo = ast.newPrimitiveType(PrimitiveType.SHORT);
}
if (ast.resolveWellKnownType("char").isEqualTo(variableType))
castTo = ast.newPrimitiveType(PrimitiveType.CHAR);
if (ast.resolveWellKnownType("byte").isEqualTo(variableType))
castTo = ast.newPrimitiveType(PrimitiveType.BYTE);
if (ast.resolveWellKnownType("short").isEqualTo(variableType))
castTo = ast.newPrimitiveType(PrimitiveType.SHORT);
if (castTo != null) {
CastExpression cast = ast.newCastExpression();
if (ASTNodes.needsParentheses(expression)) {
ParenthesizedExpression parenthesized = ast
.newParenthesizedExpression();
parenthesized.setExpression(expression);
cast.setExpression(parenthesized);
} else {
cast.setExpression(expression);
}
cast.setType(castTo);
return cast;
} else {
return expression;
}
}
}