下面列出了怎么用org.eclipse.jdt.core.dom.SimpleType的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Finding methods with change in exception list
* @param version1
* @param version2
*/
private void findChangedExceptionTypeMethods(APIVersion version1, APIVersion version2) {
for(TypeDeclaration typeVersion1 : version1.getApiAcessibleTypes()){
if(version2.containsAccessibleType(typeVersion1)){
for(MethodDeclaration methodVersion1 : typeVersion1.getMethods()){
if(this.isMethodAcessible(methodVersion1)){
MethodDeclaration methodVersion2 = version2.getEqualVersionMethod(methodVersion1, typeVersion1);
if(this.isMethodAcessible(methodVersion2)){
List<SimpleType> exceptionsVersion1 = methodVersion1.thrownExceptionTypes();
List<SimpleType> exceptionsVersion2 = methodVersion2.thrownExceptionTypes();
if(exceptionsVersion1.size() != exceptionsVersion2.size() || (this.diffListExceptions(exceptionsVersion1, exceptionsVersion2))) {
String nameMethod = this.getSimpleNameMethod(methodVersion1);
String nameClass = UtilTools.getPath(typeVersion1);
String description = this.description.exception(nameMethod, exceptionsVersion1, exceptionsVersion2, nameClass);
this.addChange(typeVersion1, methodVersion1, Category.METHOD_CHANGE_EXCEPTION_LIST, true, description);
}
}
}
}
}
}
}
public String exception(final String nameMethodBefore, final List<SimpleType> listExceptionBefore, final List<SimpleType> listExceptionAfter, final String nameClassBefore){
String message = "";
message += "<br><code>" + nameMethodBefore +"</code>";
String listBefore = (listExceptionBefore == null || listExceptionBefore.isEmpty()) ? "" : listExceptionBefore.toString();
String listAfter = (listExceptionAfter == null || listExceptionAfter.isEmpty())? "" : listExceptionAfter.toString();
if(!UtilTools.isNullOrEmpty(listBefore) && !UtilTools.isNullOrEmpty(listAfter)){
message += "<br>changed the list exception";
message += "<br>from <code>" + listBefore + "</code>";
message += "<br>to <code>" + listAfter + "</code>";
}
if(UtilTools.isNullOrEmpty(listBefore) && !UtilTools.isNullOrEmpty(listAfter)){
message += "<br>added list exception " + listAfter + "</code>";
}
if(!UtilTools.isNullOrEmpty(listBefore) && UtilTools.isNullOrEmpty(listAfter)){
message += "<br>removed list exception " + listBefore + "</code>";
}
message += "<br>in <code>" + nameClassBefore +"</code>";
message += "<br>";
return message;
}
public static Object provideAnswer(InvocationOnMock inv) {
Type type = ((BuilderField) inv.getArguments()[0]).getFieldType();
if (type instanceof ParameterizedType) {
Type baseType = ((ParameterizedType) type).getType();
if (baseType instanceof SimpleType) {
String name = ((SimpleType) baseType).getName().getFullyQualifiedName();
// if name is fully qualified
if (recognisedClasses.contains(name)) {
return Optional.ofNullable(name);
}
Optional<String> found = recognisedClasses.stream()
.filter(fqn -> fqn.endsWith("." + name))
.findFirst();
if (found.isPresent()) {
return found;
}
}
}
return Optional.of("some.other.value");
}
@Override
public boolean visit(SimpleType node) {
if (node.getAST().apiLevel() >= AST.JLS10 && node.isVar()) {
int offset= node.getStartPosition();
int length= node.getLength();
if (offset > -1 && length > 0) {
for (int i= 0; i < fJobSemanticHighlightings.length; i++) {
SemanticHighlightingCore semanticHighlighting = fJobSemanticHighlightings[i];
if (semanticHighlighting instanceof VarKeywordHighlighting) {
addPosition(offset, length, fJobHighlightings.get(i));
return false;
}
}
}
}
return true;
}
private static void addEnhancedForWithoutTypeProposals(ICompilationUnit cu, ASTNode selectedNode,
Collection<ChangeCorrectionProposal> proposals) {
if (selectedNode instanceof SimpleName && (selectedNode.getLocationInParent() == SimpleType.NAME_PROPERTY || selectedNode.getLocationInParent() == NameQualifiedType.NAME_PROPERTY)) {
ASTNode type= selectedNode.getParent();
if (type.getLocationInParent() == SingleVariableDeclaration.TYPE_PROPERTY) {
SingleVariableDeclaration svd= (SingleVariableDeclaration) type.getParent();
if (svd.getLocationInParent() == EnhancedForStatement.PARAMETER_PROPERTY) {
if (svd.getName().getLength() == 0) {
SimpleName simpleName= (SimpleName) selectedNode;
String name= simpleName.getIdentifier();
int relevance= StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7;
String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_create_loop_variable_description, BasicElementLabels.getJavaElementName(name));
proposals.add(new NewVariableCorrectionProposal(label, cu, NewVariableCorrectionProposal.LOCAL,
simpleName, null, relevance));
}
}
}
}
}
private ParameterizedType createPrivilegedActionType(ASTRewrite rewrite, ClassInstanceCreation classLoaderCreation) {
AST ast = rewrite.getAST();
Name privilegedActionName;
if (isUpdateImports()) {
privilegedActionName = ast.newSimpleName(PrivilegedAction.class.getSimpleName());
} else {
privilegedActionName = ast.newName(PrivilegedAction.class.getName());
}
SimpleType rawPrivilegedActionType = ast.newSimpleType(privilegedActionName);
ParameterizedType privilegedActionType = ast.newParameterizedType(rawPrivilegedActionType);
Type typeArgument = (Type) rewrite.createCopyTarget(classLoaderCreation.getType());
List<Type> typeArguments = checkedList(privilegedActionType.typeArguments());
typeArguments.add(typeArgument);
return privilegedActionType;
}
private void addTypeQualification(final Type type, final CompilationUnitRewrite targetRewrite, final TextEditGroup group) {
Assert.isNotNull(type);
Assert.isNotNull(targetRewrite);
final ITypeBinding binding= type.resolveBinding();
if (binding != null) {
final ITypeBinding declaring= binding.getDeclaringClass();
if (declaring != null) {
if (type instanceof SimpleType) {
final SimpleType simpleType= (SimpleType) type;
addSimpleTypeQualification(targetRewrite, declaring, simpleType, group);
} else if (type instanceof ParameterizedType) {
final ParameterizedType parameterizedType= (ParameterizedType) type;
final Type rawType= parameterizedType.getType();
if (rawType instanceof SimpleType)
addSimpleTypeQualification(targetRewrite, declaring, (SimpleType) rawType, group);
}
}
}
}
public static ParameterizedType[] inferArguments(SimpleType[] types, InferTypeArgumentsUpdate update, InferTypeArgumentsTCModel model, CompilationUnitRewrite rewrite) {
for (int i= 0; i < types.length; i++) {
types[i].setProperty(REWRITTEN, null);
}
List<ParameterizedType> result= new ArrayList<ParameterizedType>();
HashMap<ICompilationUnit, CuUpdate> updates= update.getUpdates();
Set<Entry<ICompilationUnit, CuUpdate>> entrySet= updates.entrySet();
for (Iterator<Entry<ICompilationUnit, CuUpdate>> iter= entrySet.iterator(); iter.hasNext();) {
Entry<ICompilationUnit, CuUpdate> entry= iter.next();
rewrite.setResolveBindings(false);
CuUpdate cuUpdate= entry.getValue();
for (Iterator<CollectionElementVariable2> cvIter= cuUpdate.getDeclarations().iterator(); cvIter.hasNext();) {
ConstraintVariable2 cv= cvIter.next();
ParameterizedType newNode= rewriteConstraintVariable(cv, rewrite, model, false, types);
if (newNode != null)
result.add(newNode);
}
}
return result.toArray(new ParameterizedType[result.size()]);
}
/**
* For {@link Name} or {@link Type} nodes, returns the topmost {@link Type} node
* that shares the same type binding as the given node.
*
* @param node an ASTNode
* @return the normalized {@link Type} node or the original node
*/
public static ASTNode getNormalizedNode(ASTNode node) {
ASTNode current= node;
// normalize name
if (QualifiedName.NAME_PROPERTY.equals(current.getLocationInParent())) {
current= current.getParent();
}
// normalize type
if (QualifiedType.NAME_PROPERTY.equals(current.getLocationInParent())
|| SimpleType.NAME_PROPERTY.equals(current.getLocationInParent())
|| NameQualifiedType.NAME_PROPERTY.equals(current.getLocationInParent())) {
current= current.getParent();
}
// normalize parameterized types
if (ParameterizedType.TYPE_PROPERTY.equals(current.getLocationInParent())) {
current= current.getParent();
}
return current;
}
private static boolean isRawTypeReference(ASTNode node) {
if (!(node instanceof SimpleType))
return false;
ITypeBinding typeBinding= ((SimpleType) node).resolveBinding();
if (typeBinding == null)
return false;
ITypeBinding binding= typeBinding.getTypeDeclaration();
if (binding == null)
return false;
ITypeBinding[] parameters= binding.getTypeParameters();
if (parameters.length == 0)
return false;
return true;
}
public static ITypeBinding guessBindingForTypeReference(ASTNode node) {
StructuralPropertyDescriptor locationInParent= node.getLocationInParent();
if (locationInParent == QualifiedName.QUALIFIER_PROPERTY) {
return null; // can't guess type for X.A
}
if (locationInParent == SimpleType.NAME_PROPERTY ||
locationInParent == NameQualifiedType.NAME_PROPERTY) {
node= node.getParent();
}
ITypeBinding binding= Bindings.normalizeTypeBinding(getPossibleTypeBinding(node));
if (binding != null) {
if (binding.isWildcardType()) {
return normalizeWildcardType(binding, true, node.getAST());
}
}
return binding;
}
private static ITypeBinding extractExpressionType(SimpleType variableIdentifier) {
ScopeAnalyzer analyzer= new ScopeAnalyzer((CompilationUnit) variableIdentifier.getRoot());
// get the name of the variable to search the type for
Name name= null;
if (variableIdentifier.getName() instanceof SimpleName) {
name= variableIdentifier.getName();
} else if (variableIdentifier.getName() instanceof QualifiedName) {
name= ((QualifiedName) variableIdentifier.getName()).getName();
}
// analyze variables which are available in the scope at the position of the quick assist invokation
IBinding[] declarationsInScope= analyzer.getDeclarationsInScope(name.getStartPosition(), ScopeAnalyzer.VARIABLES);
for (int i= 0; i < declarationsInScope.length; i++) {
IBinding currentVariable= declarationsInScope[i];
if (((IVariableBinding) currentVariable).getName().equals(name.getFullyQualifiedName())) {
return ((IVariableBinding) currentVariable).getType();
}
}
return null;
}
private static void addEnhancedForWithoutTypeProposals(ICompilationUnit cu, ASTNode selectedNode, Collection<ICommandAccess> proposals) {
if (selectedNode instanceof SimpleName && (selectedNode.getLocationInParent() == SimpleType.NAME_PROPERTY || selectedNode.getLocationInParent() == NameQualifiedType.NAME_PROPERTY)) {
ASTNode type= selectedNode.getParent();
if (type.getLocationInParent() == SingleVariableDeclaration.TYPE_PROPERTY) {
SingleVariableDeclaration svd= (SingleVariableDeclaration) type.getParent();
if (svd.getLocationInParent() == EnhancedForStatement.PARAMETER_PROPERTY) {
if (svd.getName().getLength() == 0) {
SimpleName simpleName= (SimpleName) selectedNode;
String name= simpleName.getIdentifier();
int relevance= StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7;
String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_create_loop_variable_description, BasicElementLabels.getJavaElementName(name));
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
proposals.add(new NewVariableCorrectionProposal(label, cu, NewVariableCorrectionProposal.LOCAL, simpleName, null, relevance, image));
}
}
}
}
}
private static boolean isQualifiedType(Type type) {
if(type instanceof SimpleType) {
SimpleType simpleType = (SimpleType)type;
Name name = simpleType.getName();
if(name instanceof QualifiedName) {
return true;
}
}
else if(type instanceof QualifiedType) {
QualifiedType qualifiedType = (QualifiedType)type;
Type qualifier = qualifiedType.getQualifier();
return isQualifiedType(qualifier);
}
else if(type instanceof ArrayType) {
ArrayType arrayType = (ArrayType)type;
Type elementType = arrayType.getElementType();
return isQualifiedType(elementType);
}
else if(type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType)type;
Type erasureType = parameterizedType.getType();
return isQualifiedType(erasureType);
}
return false;
}
@Override
public boolean visit(SimpleType node) {
if (node.isVar() && showJava10VarType) {
JavaVarTypeCodeMining m = new JavaVarTypeCodeMining(node, viewer, provider);
minings.add(m);
}
return super.visit(node);
}
/**
* @param parameterListException
* @param exception
* @return true, if the list contains the "exception"
*/
private boolean containsExceptionList(List<SimpleType> parameterListException, SimpleType exception){
for(SimpleType simpleType : parameterListException){
if(simpleType.getName().toString().equals(exception.getName().toString())){
return true;
}
}
return false;
}
/**
* @param listExceptionsVersion1
* @param listExceptionsVersion2
* @return true, if the exception does not exist in exception list 2.
*/
private boolean diffListExceptions(List<SimpleType> listExceptionsVersion1, List<SimpleType> listExceptionsVersion2){
for(SimpleType exceptionVersion1 : listExceptionsVersion1){
if(!this.containsExceptionList(listExceptionsVersion2, exceptionVersion1)){
return true;
}
}
return false;
}
/**
* @return a String representation of 'type'. Handles qualified, simple and parameterized types.
*/
@Nullable
private String getNameOfType(Type type) {
if (type instanceof QualifiedType) {
return extractTypeNameWithoutGenerics((QualifiedType) type);
}
if (type instanceof SimpleType) {
return ((SimpleType) type).getName().getFullyQualifiedName();
}
if (type instanceof ParameterizedType) {
return getNameOfType(((ParameterizedType) type).getType());
}
return null;
}
@Override
public boolean visit(SimpleType node) {
ASTNode parent = node.getParent();
if (parent instanceof ClassInstanceCreation) { // For ClassInstanceCreation "new E()", "E" should be highlighted as 'function' instead of 'type'
addToken(node, TokenType.FUNCTION, NO_MODIFIERS);
return false;
}
return super.visit(node);
}
@Override
public void endVisit(SimpleType node) {
if (skipNode(node)) {
return;
}
assignFlowInfo(node, node.getName());
}
private static String getPrettyTypeName(Type type) {
if (type.isArrayType()) {
return getPrettyTypeName((ArrayType) type);
} else if (type.isParameterizedType()) {
return getPrettyTypeName((ParameterizedType) type);
} else if (type.isPrimitiveType()) {
return getPrettyTypeName((PrimitiveType) type);
} else if (type.isQualifiedType()) {
return getPrettyTypeName((QualifiedType) type);
} else if (type.isSimpleType()) {
return getPrettyTypeName((SimpleType) type);
} else {
return "";
}
}
@Override
public boolean visit(final QualifiedName it) {
it.getQualifier().accept(this);
if (((this.fallBackStrategy && this._aSTFlattenerUtils.isStaticMemberCall(it)) &&
(!((it.getParent() instanceof SimpleType) || (it.getParent() instanceof ImportDeclaration))))) {
this.appendToBuffer("::");
} else {
this.appendToBuffer(".");
}
it.getName().accept(this);
return false;
}
public boolean isMissingType(final Type type) {
if ((type instanceof SimpleType)) {
boolean _isSimpleName = ((SimpleType)type).getName().isSimpleName();
if (_isSimpleName) {
Name _name = ((SimpleType)type).getName();
return "MISSING".equals(((SimpleName) _name).getIdentifier());
}
}
return false;
}
@Override
public boolean visit(final SimpleType node) {
if (node.resolveBinding() == null) {
return true;
}
getTypeBindingParents(node.resolveBinding());
return super.visit(node);
}
/**
* Add exception related features.
*
* @param md
* @param features
*/
private void addExceptionFeatures(final MethodDeclaration md,
final Set<String> features) {
checkArgument(activeFeatures.contains(AvailableFeatures.EXCEPTIONS));
for (final Object exception : md.thrownExceptionTypes()) {
final SimpleType ex = (SimpleType) exception;
features.add("thrownException:" + ex.toString());
}
}
public boolean visit(SimpleType node) {
Name name = node.getName();
types.add(name.getFullyQualifiedName());
if(current.getUserObject() != null) {
AnonymousClassDeclarationObject anonymous = (AnonymousClassDeclarationObject)current.getUserObject();
anonymous.getTypes().add(name.getFullyQualifiedName());
}
return false;
}
@Override
public boolean visit(FieldDeclaration node) {
field ++;
org.eclipse.jdt.core.dom.Type type = node.getType();
if (type instanceof SimpleType && ((SimpleType)type).getName().getFullyQualifiedName().equals("String")) {
stringField += node.fragments().size();
stringField2 += node.fragments().size();
}
return true;
}
/**
* All types should be ensured first via this method. We first check to see if
* the binding is resolvable (not null) If it is not null we ensure the type
* from the binding (the happy case) If the type is null we recover what we know
* (for example, the name of a simple type) In the worst case we return the
* {@link #unknownType()}
*/
private Type ensureTypeFromDomType(org.eclipse.jdt.core.dom.Type domType) {
ITypeBinding binding = domType.resolveBinding();
if (binding != null)
return ensureTypeFromTypeBinding(binding);
if (domType.isSimpleType())
return ensureTypeNamedInUnknownNamespace(((SimpleType) domType).getName().toString());
if (domType.isParameterizedType())
return ensureTypeNamedInUnknownNamespace(
((org.eclipse.jdt.core.dom.ParameterizedType) domType).getType().toString());
return unknownType();
}
@Override
public boolean visit(final SimpleType node) {
if (node.resolveBinding() == null) {
return true;
}
getTypeBindingParents(node.resolveBinding());
return super.visit(node);
}
/**
* Add exception related features.
*
* @param md
* @param features
*/
private void addExceptionFeatures(final MethodDeclaration md,
final Set<String> features) {
checkArgument(activeFeatures.contains(AvailableFeatures.EXCEPTIONS));
for (final Object exception : md.thrownExceptionTypes()) {
final SimpleType ex = (SimpleType) exception;
features.add("thrownException:" + ex.toString());
}
}