alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

/*
 *                 Sun Public License Notice
 *
 * The contents of this file are subject to the Sun Public License
 * Version 1.0 (the "License"). You may not use this file except in
 * compliance with the License. A copy of the License is available at
 * http://www.sun.com/
 *
 * The Original Code is NetBeans. The Initial Developer of the Original
 * Code is Sun Microsystems, Inc. Portions Copyright 1997-2003 Sun
 * Microsystems, Inc. All Rights Reserved.
 */
package org.netbeans.modules.javacore.jmiimpl.javamodel;

import java.lang.reflect.Modifier;
import java.util.*;
import org.netbeans.jmi.javamodel.*;
import org.netbeans.lib.java.parser.ASTree;
import org.netbeans.mdr.storagemodel.StorableObject;
import org.netbeans.modules.javacore.parser.ASTProvider;
import org.netbeans.modules.javacore.parser.ElementInfo;
import org.netbeans.modules.javacore.parser.MethodInfo;
import org.netbeans.modules.javacore.parser.TypeRef;

/**
 * Implementation of Parameter object instance interface.
 *
 * @author  Martin Matula
 * @author  Pavel Flaska
 */
public abstract class MethodImpl extends CallableFeatureImpl implements Method {
    private static final ElementInfo DEFAULT_INFO = new MethodInfo(null, MethodInfo.METHOD_TYPE, null, 0, null, null, null, null, null);

    private TypeReference typeName;

    /** Creates a new instance of MethodImpl */
    public MethodImpl(StorableObject s) {
        super(s);
    }

    public String toString() {
        return "method " + getName(); // NOI18N
    }

    protected ElementInfo getDefaultInfo() {
        return DEFAULT_INFO;
    }

    public TypeReference getTypeName() {
        if (!elementsInited) {
            initASTElements();
        }
        return typeName;
    }

    public void setTypeName(TypeReference typeName) {
        _setTypeName(typeName, typeReferenceToTypeRef(typeName));
    }
    
    private void _setTypeName(TypeReference typeName, TypeRef typeRef) {
        objectChanged(CHANGED_TYPE);
        if (elementsInited) {
            changeChild(getTypeName(), typeName);
            this.typeName = typeName;
        }
        setTypeRef(typeRef);
    }
    
    /**
     * Returns the value of reference type.
     * @return Value of reference type.
     */
    public Type getType() {
        return resolveType(getTypeRef());
    }

    /**
     * Sets the value of reference type. See {@link #getType} for description
     * on the reference.
     * @param newValue New value to be set.
     */
    public void setType(Type newValue) {
        TypeRef tr = typeToTypeRef(newValue);
        _setTypeName((TypeReference) typeRefToTypeReference(tr), tr);
    }

    protected void initASTElements() {
        elementsInited = false;
        ElementInfo info = getElementInfo();
        ASTree tree = info.getTypeAST(this);
        typeName = (TypeReference) initOrCreate(typeName, tree);
        super.initASTElements();
        elementsInited = true;
    }

    protected void setData(List annotations, java.lang.String javadocText, JavaDoc javadoc, StatementBlock body, java.lang.String bodyText, List typeArguments, List parameters, List exceptionNames, TypeReference typeName, int dimCount) {
        super.setData(annotations, javadocText, javadoc, body, bodyText, typeArguments, parameters, exceptionNames);
        changeChild(null, typeName);
        this.typeName = typeName;
    }

    protected void resetASTElements() {
        if (elementsInited) {
            if (typeName != null) {
                TypeReference temp = typeName;
                changeChild(typeName, null);
                typeName = null;
                temp.refDelete();
            }
            super.resetASTElements();
        }
    }

    public void replaceChild(Element oldElement, Element newElement) {
        if (elementsInited) {
            if (oldElement.equals(typeName)) {
                setTypeName((TypeReference) newElement);
                return;
            }
        }
        super.replaceChild(oldElement, newElement);
    }

    public List getChildren() {
        List list = new ArrayList();
        addIfNotNull(list, getTypeName());
        list.addAll(super.getChildren());
        return list;
    }

    protected List getInitedChildren() {
        List list = super.getInitedChildren();
        if (elementsInited) {
            addIfNotNull(list, typeName);
        }
        return list;
    }

    // .........................................................................
    // printing and formatting fuctionality
    // .........................................................................

    /**
     * Implementation of abstract method from CallableFeatureImpl. Appends
     * to buffer return type and method name separated by space.
     *
     * @param  buf  buffer to append to
     */
    void generateTypeAndName(StringBuffer buf) {
        MetadataElement melem = (MetadataElement)getTypeName();
        if (melem != null) {
            buf.append(melem.getSourceText());
        } else {
            buf.append(getType().getName());
        }
        buf.append(' ');
        buf.append(getName());
        formatElementPart(CALLABLE_IDENTIFIER, buf);
    }

    /**
     * Returns source code representation of this object.
     *
     * @return  source code representation of the object.
     */
    public String getSourceText() {
        String origElem;
        if ((origElem = checkChange()) != null)
            return origElem;
        // we have element which is new or changed and moved.
        // todo (#pf): it is possible to leave formatting and comments section
        // as they are in the original element if the element is regenerated.
        // Because it is only rare case, we do not solve it now.
        if (!elementsInited) {
            initASTElements();
        }
        StringBuffer buf = new StringBuffer();
        generateHeader(buf);
        int modifiers = getSourceModifiers();
        boolean parentAbstract = false;
        if (refImmediateComposite() instanceof JavaClass) {
            JavaClass jc = (JavaClass) refImmediateComposite();
            parentAbstract = jc.isInterface();
        }
        if (!parentAbstract && (modifiers & Modifier.ABSTRACT) != Modifier.ABSTRACT) {
            generateBody(buf);
        }
        else
            buf.append(';');
        return buf.toString();
    }

    protected void _delete() {
        if (elementsInited) {
            deleteChild(getTypeName());
        }
        super._delete();
    }
    
    public void getDiff(List diffList) {
        MethodInfo astInfo = (MethodInfo) getElementInfo();
        ASTProvider parser = getParser();
        ASTree tree = getASTree();
        ASTree[] children = tree.getSubTrees();

        // javadoc print
        replaceJavaDoc(diffList);
        // modifier print
        ASTree type = children[2];
        if (isChanged(CHANGED_MODIFIERS) || isChanged(CHANGED_ANNOTATION)) {
            diffModifiers(diffList, type == null ? children[3] : type, parser);
        }
        
        getTypeParamsDiff(diffList);
        // type
        getChildDiff(diffList, parser, type, (MetadataElement) getTypeName(), CHANGED_TYPE);
        // name
        ASTree declarator = tree.getSubTrees()[3];
        if (isChanged(CHANGED_NAME)) {
            String newName = getName();
            replaceNode(diffList, parser, declarator.getSubTrees()[0], newName, 0, null);
        }
        // parameters
        String comma = formatElementPart(COMMA);
        int endOffset = parser.getToken(declarator.getLastToken()).getStartOffset();
        getCollectionDiff(diffList, parser, CHANGED_PARAMETERS,
            astInfo.parameters, getParameters(), endOffset, comma);
        // exceptions
        int startOffset = parser.getToken(declarator.getLastToken()).getEndOffset();
        getCollectionDiff(diffList, parser, CHANGED_THROWS, tree.getSubTrees()[4],
                getExceptionNames(), startOffset, comma, formatElementPart(THROWS_KEYWORD));
        // body print
        createBodyDiffs(diffList);
    }

    /**
     */
    protected ASTree getPartTree(ElementPartKind part) {
        ASTree[] children = getASTree().getSubTrees();
        if (ElementPartKindEnum.NAME.equals(part))
            return children[3].getSubTrees()[0];

        throw new IllegalArgumentException("Invalid part for this element: " + part); // NOI18N
    }

    /**
     */
    protected ASTree getPartStartTree(ElementPartKind part) {
        if (ElementPartKindEnum.HEADER.equals(part)) {
            return getASTree();
        }
        return super.getPartStartTree(part);
    }

    /**
     */
    protected ASTree getPartEndTree(ElementPartKind part) {
        if (ElementPartKindEnum.HEADER.equals(part)) {
            ASTree[] headerParts = getASTree().getSubTrees();
            for (int i = 4; true; i--) {
                ASTree result = headerParts[i];
                if (result != null) {
                    return result;
                }
            }
        }
        return super.getPartEndTree(part);
    }

    public Collection getReferences() {
        return findDependencies(true, false, false);
    }
    
    public boolean signatureEquals(Method m) {
        if (!this.getName().equals(m.getName()))
            return false;
        
        if (this.getParameters().size() != m.getParameters().size())
            return false;
        
        Iterator parsIter1 = this.getParameters().iterator();
        Iterator parsIter2 = m.getParameters().iterator();
        while (parsIter1.hasNext()) {
            Type t1 = TypeClassImpl.getRealType(((Parameter) parsIter1.next()).getType());
            Type t2 = TypeClassImpl.getRealType(((Parameter) parsIter2.next()).getType());
            if (!t1.equals(t2)) {
                return false;
            }
        }
        return true;
    }
    
    public Collection getOverridenMethods() {
        Collection result = new LinkedHashSet(2);
        
        ClassDefinition declaringClass = this.getDeclaringClass();
        
        List params = new ArrayList();
        for (Iterator i = this.getParameters().iterator(); i.hasNext(); params.add(((Parameter)i.next()).getType()));
        
        Iterator i = declaringClass.getInterfaces().iterator();
        while (i.hasNext()) {
            ClassDefinition jc = (ClassDefinition) i.next();
            Method m = jc.getMethod(this.getName(), params, true);
            if (m!=null) {
                result.add(m);
            }
        }

        ClassDefinition parent = declaringClass.getSuperClass();
        while (parent != null) {
            Method m = parent.getMethod(this.getName(), params, false);
            if (m!=null) {
                if (m instanceof ParameterizedTypeImpl.Wrapper) {
                    m = (Method) ((ParameterizedTypeImpl.Wrapper) m).getWrappedObject();
                }
                result.addAll(((MethodImpl) m).getOverridenMethods());
                result.add(m);
            }
            parent = parent.getSuperClass();
        }
        return result;
    }
}
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.