Example usage for org.objectweb.asm Opcodes ACC_PRIVATE

List of usage examples for org.objectweb.asm Opcodes ACC_PRIVATE

Introduction

In this page you can find the example usage for org.objectweb.asm Opcodes ACC_PRIVATE.

Prototype

int ACC_PRIVATE

To view the source code for org.objectweb.asm Opcodes ACC_PRIVATE.

Click Source Link

Usage

From source file:org.mbte.groovypp.compiler.bytecode.PropertyUtil.java

License:Apache License

public static BytecodeExpr createSetProperty(ASTNode parent, CompilerTransformer compiler, String propName,
        BytecodeExpr object, BytecodeExpr value, Object prop) {
    if (prop instanceof MethodNode) {
        return new ResolvedMethodBytecodeExpr.Setter(parent, (MethodNode) prop, object,
                new ArgumentListExpression(value), compiler);
    }//www.j  a  v a  2  s. c  om

    if (prop instanceof PropertyNode) {
        final PropertyNode propertyNode = (PropertyNode) prop;
        if ((propertyNode.getModifiers() & Opcodes.ACC_FINAL) != 0) {
            final FieldNode fieldNode = compiler.findField(propertyNode.getDeclaringClass(), propName);
            return new ResolvedFieldBytecodeExpr(parent, fieldNode, object, value, compiler);
        }

        return new ResolvedPropertyBytecodeExpr(parent, propertyNode, object, value, compiler);
    }

    if (prop instanceof FieldNode) {
        final FieldNode field = (FieldNode) prop;
        if ((field.getModifiers() & Opcodes.ACC_PRIVATE) != 0
                && field.getDeclaringClass() != compiler.classNode) {
            MethodNode setter = compiler.context.getFieldSetter(field);
            return new ResolvedMethodBytecodeExpr.Setter(parent, setter, object,
                    new ArgumentListExpression(value), compiler);
        }
        return new ResolvedFieldBytecodeExpr(parent, field, object, value, compiler);
    }

    if (prop instanceof GetUnresolved) {
        final MethodCallExpression setUnresolvedProperty = new MethodCallExpression(object,
                "setUnresolvedProperty", new ArgumentListExpression(new ConstantExpression(propName), value));
        setUnresolvedProperty.setSourcePosition(parent);
        return (BytecodeExpr) compiler.transform(setUnresolvedProperty);
    }

    final ClassNode type = object != null ? object.getType() : compiler.classNode;
    return dynamicOrFail(parent, compiler, propName, type, object, value, "assign");
}

From source file:org.mbte.groovypp.compiler.bytecode.ResolvedMethodBytecodeExpr.java

License:Apache License

public static BytecodeExpr create(ASTNode parent, MethodNode methodNode, BytecodeExpr object,
        TupleExpression bargs, CompilerTransformer compiler) {
    if ((methodNode.getModifiers() & Opcodes.ACC_PRIVATE) != 0
            && methodNode.getDeclaringClass() != compiler.classNode) {
        MethodNode delegate = compiler.context.getMethodDelegate(methodNode);
        return new ResolvedMethodBytecodeExpr(parent, delegate, object, bargs, compiler);
    } else if (methodNode instanceof ClassNodeCache.DGM
            && object instanceof VariableExpressionTransformer.Super) {
        compiler.addError("Cannot reference default groovy method '" + methodNode.getName()
                + "' using 'super'. Call the static method instead.", parent);
    }//w  w w.j  a v a 2s  .  co m
    return new ResolvedMethodBytecodeExpr(parent, methodNode, object, bargs, compiler);
}

From source file:org.mbte.groovypp.compiler.TraitASTTransform.java

License:Apache License

public void visit(ASTNode[] nodes, final SourceUnit source) {
    ModuleNode module = (ModuleNode) nodes[0];
    List<ClassNode> toProcess = new LinkedList<ClassNode>();
    final boolean forceTyped = source.getName().endsWith(".gpp");
    AnnotationNode pkgTypedAnn = getTypedAnnotation(module.getPackage());
    for (ClassNode classNode : module.getClasses()) {
        boolean process = false;
        boolean typed = false;
        for (AnnotationNode ann : classNode.getAnnotations()) {
            final String withoutPackage = ann.getClassNode().getNameWithoutPackage();
            if (withoutPackage.equals("Trait")) {
                process = true;/*from  w w  w . j  av  a  2  s  . co  m*/
            }
            if (withoutPackage.equals("Typed")) {
                typed = true;
                ann.getClassNode().setRedirect(TypeUtil.TYPED);
            }
        }

        if (forceTyped && !typed) {
            typed = true;
            classNode.addAnnotation(pkgTypedAnn != null ? pkgTypedAnn : new AnnotationNode(TypeUtil.TYPED));
        }

        if (process) {
            toProcess.add(classNode);
            if (!typed) {
                classNode.addAnnotation(pkgTypedAnn != null ? pkgTypedAnn : new AnnotationNode(TypeUtil.TYPED));
            }
        }
    }

    for (ClassNode classNode : toProcess) {
        if (classNode.isInterface() || classNode.isEnum() || classNode.isAnnotationDefinition()) {
            source.addError(new SyntaxException("@Trait can be applied only to <class>",
                    classNode.getLineNumber(), classNode.getColumnNumber()));
            continue;
        }

        if (classNode.getDeclaredConstructors().size() > 0) {
            ConstructorNode constructor = classNode.getDeclaredConstructors().get(0);
            source.addError(new SyntaxException("Constructors are not allowed in traits",
                    constructor.getLineNumber(), constructor.getColumnNumber()));
            continue;
        }

        if (classNode.getObjectInitializerStatements().size() > 0) {
            Statement initializer = classNode.getObjectInitializerStatements().get(0);
            source.addError(new SyntaxException("Object initializers are not allowed in traits",
                    initializer.getLineNumber(), initializer.getColumnNumber()));
            continue;
        }

        int mod = classNode.getModifiers();
        mod &= ~Opcodes.ACC_FINAL;
        mod |= Opcodes.ACC_ABSTRACT | Opcodes.ACC_INTERFACE;
        classNode.setModifiers(mod);

        String name = classNode.getNameWithoutPackage() + "$TraitImpl";
        String fullName = ASTHelper.dot(classNode.getPackageName(), name);

        InnerClassNode innerClassNode = new InnerClassNode(classNode, fullName,
                ACC_PUBLIC | ACC_STATIC | ACC_ABSTRACT, ClassHelper.OBJECT_TYPE, new ClassNode[] { classNode },
                null);
        AnnotationNode typedAnn = new AnnotationNode(TypeUtil.TYPED);
        final Expression member = getTypedAnnotation(classNode).getMember("debug");
        if (member != null && member instanceof ConstantExpression
                && ((ConstantExpression) member).getValue().equals(Boolean.TRUE))
            typedAnn.addMember("debug", ConstantExpression.TRUE);
        innerClassNode.addAnnotation(typedAnn);

        innerClassNode.setGenericsTypes(classNode.getGenericsTypes());

        ClassNode superClass = classNode.getSuperClass();
        if (!ClassHelper.OBJECT_TYPE.equals(superClass)) {
            ClassNode[] ifaces = classNode.getInterfaces();
            ClassNode[] newIfaces = new ClassNode[ifaces.length + 1];
            newIfaces[0] = superClass;
            System.arraycopy(ifaces, 0, newIfaces, 1, ifaces.length);
            classNode.setSuperClass(ClassHelper.OBJECT_TYPE);
            classNode.setInterfaces(newIfaces);
        }

        classNode.getModule().addClass(innerClassNode);

        innerClassNode.addMethod("getMetaClass", ACC_PUBLIC | ACC_ABSTRACT, ClassHelper.METACLASS_TYPE,
                Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null);
        innerClassNode.addMethod("setMetaClass", ACC_PUBLIC | ACC_ABSTRACT, ClassHelper.VOID_TYPE,
                new Parameter[] { new Parameter(ClassHelper.METACLASS_TYPE, "value") }, ClassNode.EMPTY_ARRAY,
                null);
        innerClassNode.addMethod("getProperty", ACC_PUBLIC | ACC_ABSTRACT, ClassHelper.OBJECT_TYPE,
                new Parameter[] { new Parameter(ClassHelper.STRING_TYPE, "name") }, ClassNode.EMPTY_ARRAY,
                null);
        innerClassNode.addMethod("setProperty", ACC_PUBLIC | ACC_ABSTRACT, ClassHelper.VOID_TYPE,
                new Parameter[] { new Parameter(ClassHelper.STRING_TYPE, "name"),
                        new Parameter(ClassHelper.OBJECT_TYPE, "value") },
                ClassNode.EMPTY_ARRAY, null);
        innerClassNode.addMethod("invokeMethod", ACC_PUBLIC | ACC_ABSTRACT, ClassHelper.OBJECT_TYPE,
                new Parameter[] { new Parameter(ClassHelper.STRING_TYPE, "name"),
                        new Parameter(ClassHelper.OBJECT_TYPE, "args") },
                ClassNode.EMPTY_ARRAY, null);

        for (FieldNode fieldNode : classNode.getFields()) {
            //                if (fieldNode.isStatic())
            //                    continue;

            final String getterName = "get" + Verifier.capitalize(fieldNode.getName());
            MethodNode getter = classNode.getGetterMethod(getterName);
            if (getter == null) {
                getter = classNode.addMethod(getterName, ACC_PUBLIC | ACC_ABSTRACT, fieldNode.getType(),
                        Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null);
                addFieldAnnotation(innerClassNode, fieldNode, getter);
            }

            // We need the second getter (and setter) to compile non-synthetic first one referring to the field.
            // The references inside the first one will be retargeted to the second one.
            final MethodNode realGetter = classNode.addMethod("get$" + fieldNode.getName(),
                    ACC_PUBLIC | ACC_ABSTRACT, fieldNode.getType(), Parameter.EMPTY_ARRAY,
                    ClassNode.EMPTY_ARRAY, null);
            addFieldAnnotation(innerClassNode, fieldNode, realGetter);

            final String setterName = "set" + Verifier.capitalize(fieldNode.getName());
            Parameter valueParam = new Parameter(fieldNode.getType(), "$value");
            MethodNode setter = classNode.getSetterMethod(setterName);
            if (setter == null) {
                setter = classNode.addMethod(setterName, ACC_PUBLIC | ACC_ABSTRACT, ClassHelper.VOID_TYPE,
                        new Parameter[] { valueParam }, ClassNode.EMPTY_ARRAY, null);
                addFieldAnnotation(innerClassNode, fieldNode, setter);
            }

            final MethodNode realSetter = classNode.addMethod("set$" + fieldNode.getName(),
                    ACC_PUBLIC | ACC_ABSTRACT, ClassHelper.VOID_TYPE, new Parameter[] { valueParam },
                    ClassNode.EMPTY_ARRAY, null);
            addFieldAnnotation(innerClassNode, fieldNode, realSetter);

            if (fieldNode.hasInitialExpression()) {
                final Expression initial = fieldNode.getInitialValueExpression();
                fieldNode.setInitialValueExpression(null);

                final MethodNode initMethod = innerClassNode.addMethod("__init_" + fieldNode.getName(),
                        ACC_PUBLIC | ACC_STATIC, ClassHelper.VOID_TYPE,
                        new Parameter[] { new Parameter(classNode, "$self") }, ClassNode.EMPTY_ARRAY,
                        new BlockStatement());

                final PropertyExpression prop = new PropertyExpression(new VariableExpression("$self"),
                        fieldNode.getName());
                prop.setSourcePosition(fieldNode);
                final CastExpression cast = new CastExpression(fieldNode.getType(), initial);
                cast.setSourcePosition(initial);
                final BinaryExpression assign = new BinaryExpression(prop,
                        Token.newSymbol(Types.ASSIGN, -1, -1), cast);
                assign.setSourcePosition(initial);
                final ExpressionStatement assignExpr = new ExpressionStatement(assign);
                assignExpr.setSourcePosition(initial);
                ((BlockStatement) initMethod.getCode()).addStatement(assignExpr);
            }

            innerClassNode.addField(fieldNode);
        }

        classNode.getFields().clear();
        classNode.getProperties().clear();

        for (MethodNode methodNode : classNode.getMethods()) {
            if (methodNode.getCode() == null)
                continue;

            if (methodNode.isStatic()) {
                source.addError(new SyntaxException("Static methods are not allowed in traits",
                        methodNode.getLineNumber(), methodNode.getColumnNumber()));
            }

            if (!methodNode.isPublic()) {
                source.addError(new SyntaxException("Non-public methods are not allowed in traits",
                        methodNode.getLineNumber(), methodNode.getColumnNumber()));
            }

            mod = methodNode.getModifiers();
            mod &= ~(Opcodes.ACC_FINAL | Opcodes.ACC_PROTECTED | Opcodes.ACC_PRIVATE);
            mod |= Opcodes.ACC_ABSTRACT | Opcodes.ACC_PUBLIC;
            methodNode.setModifiers(mod);

            Parameter[] parameters = methodNode.getParameters();

            Parameter[] newParameters = new Parameter[parameters.length + 1];
            final Parameter self = new Parameter(classNode, "$self");
            newParameters[0] = self;
            System.arraycopy(parameters, 0, newParameters, 1, parameters.length);

            MethodNode newMethod = innerClassNode.addMethod(methodNode.getName(), ACC_PUBLIC,
                    methodNode.getReturnType(), newParameters, ClassNode.EMPTY_ARRAY, methodNode.getCode());
            ArrayList<GenericsType> gt = new ArrayList<GenericsType>();
            if (classNode.getGenericsTypes() != null)
                for (int i = 0; i < classNode.getGenericsTypes().length; i++) {
                    GenericsType genericsType = classNode.getGenericsTypes()[i];
                    gt.add(genericsType);
                }
            if (methodNode.getGenericsTypes() != null)
                for (int i = 0; i < methodNode.getGenericsTypes().length; i++) {
                    GenericsType genericsType = methodNode.getGenericsTypes()[i];
                    gt.add(genericsType);
                }

            if (!gt.isEmpty())
                newMethod.setGenericsTypes(gt.toArray(new GenericsType[gt.size()]));

            AnnotationNode annotationNode = new AnnotationNode(TypeUtil.HAS_DEFAULT_IMPLEMENTATION);
            annotationNode.addMember("value", new ClassExpression(innerClassNode));
            methodNode.addAnnotation(annotationNode);

            methodNode.setCode(null);
        }
    }
}

From source file:org.mbte.groovypp.compiler.transformers.ConstructorCallExpressionTransformer.java

License:Apache License

public Expression transform(ConstructorCallExpression exp, final CompilerTransformer compiler) {

    if (exp.isSuperCall() || exp.isThisCall())
        return transformSpecial(exp, compiler);

    MethodNode constructor;/*from  ww  w. j av a  2  s  . c om*/
    ClassNode type = exp.getType();

    if ((ClassHelper.isPrimitiveType(type))) {
        compiler.addError("Can't instantiate primitive type " + type.getName(), exp);
        return null;
    }

    if ((type.getModifiers() & Opcodes.ACC_ABSTRACT) != 0) {
        compiler.addError("Can't instantiate abstract type " + type.getName(), exp);
        return null;
    }

    if (type instanceof InnerClassNode) {
        InnerClassNode innerClassNode = (InnerClassNode) type;

        if (innerClassNode.isAnonymous()) {
            if (!improveWhatInnerClassVisitorDid(innerClassNode, exp, compiler))
                return null;
        }
    }

    rewriteThis0(exp, compiler);

    if (exp.getArguments() instanceof TupleExpression
            && ((TupleExpression) exp.getArguments()).getExpressions().size() == 1
            && ((TupleExpression) exp.getArguments()).getExpressions().get(0) instanceof MapExpression) {
        MapExpression me = (MapExpression) ((TupleExpression) exp.getArguments()).getExpressions().get(0);

        constructor = compiler.findConstructor(type, MAP_ARGS, null);
        if (constructor == null) {
            final ArrayList<BytecodeExpr> propSetters = new ArrayList<BytecodeExpr>();

            constructor = compiler.findConstructor(type, ClassNode.EMPTY_ARRAY, null);
            if (constructor != null) {
                for (MapEntryExpression mee : me.getMapEntryExpressions()) {

                    BytecodeExpr obj = new BytecodeExpr(mee, type) {
                        protected void compile(MethodVisitor mv) {
                            mv.visitInsn(DUP);
                        }
                    };

                    propSetters.add((BytecodeExpr) compiler
                            .transform(new BinaryExpression(new PropertyExpression(obj, mee.getKeyExpression()),
                                    Token.newSymbol(Types.ASSIGN, -1, -1), mee.getValueExpression())));
                }

                return new BytecodeExpr(exp, type) {
                    protected void compile(MethodVisitor mv) {
                        final String classInternalName = BytecodeHelper.getClassInternalName(getType());
                        mv.visitTypeInsn(NEW, classInternalName);
                        mv.visitInsn(DUP);
                        mv.visitMethodInsn(INVOKESPECIAL, classInternalName, "<init>", "()V");

                        for (BytecodeExpr prop : propSetters) {
                            prop.visit(mv);
                            if (!ClassHelper.VOID_TYPE.equals(prop.getType()))
                                pop(prop.getType(), mv);
                        }
                    }
                };
            }
        }
    }

    final TupleExpression newArgs = (TupleExpression) compiler.transform(exp.getArguments());
    final ClassNode[] argTypes = compiler.exprToTypeArray(newArgs);

    constructor = findConstructorWithClosureCoercion(type, argTypes, compiler, null);

    if (constructor != null) {
        if (!AccessibilityCheck.isAccessible(constructor.getModifiers(), constructor.getDeclaringClass(),
                compiler.classNode, null)) {
            compiler.addError("Cannot access constructor", exp);
            return null;
        }

        final Parameter[] params = constructor.getParameters();
        int base = 0;
        //            if ((type.getModifiers() & ACC_STATIC) == 0 && type.redirect() instanceof InnerClassNode) {
        //                base = 1;
        //            }
        final ArgumentListExpression finalArgs = wrapArgumentsForVarargs(newArgs, params, base);

        if ((constructor.getModifiers() & Opcodes.ACC_PRIVATE) != 0
                && constructor.getDeclaringClass() != compiler.classNode) {
            MethodNode delegate = compiler.context.getConstructorDelegate(constructor);
            return ResolvedMethodBytecodeExpr.create(exp, delegate, null, finalArgs, compiler);
        }

        // Improve type.
        GenericsType[] generics = type.redirect().getGenericsTypes();
        // We don't support inference if the method itself is parameterized.
        if (generics != null && constructor.getGenericsTypes() == null) {
            ClassNode[] paramTypes = new ClassNode[params.length];
            for (int i = 0; i < paramTypes.length; i++) {
                paramTypes[i] = params[i].getType();
            }
            ClassNode[] unified = TypeUnification.inferTypeArguments(generics, paramTypes, argTypes);
            if (TypeUnification.totalInference(unified)) {
                type = TypeUtil.withGenericTypes(type, unified);
            }
        }
        for (int i = 0; i != finalArgs.getExpressions().size(); ++i)
            finalArgs.getExpressions().set(i, compiler.cast(finalArgs.getExpressions().get(i),
                    constructor.getParameters()[i + base].getType()));

        final MethodNode constructor1 = constructor;
        final ClassNode compilerClass = compiler.classNode;
        return new BytecodeExpr(exp, type) {
            protected void compile(MethodVisitor mv) {
                final String classInternalName = BytecodeHelper.getClassInternalName(getType());
                mv.visitTypeInsn(NEW, classInternalName);
                mv.visitInsn(DUP);

                int first = 0;
                //                    if ((getType().getModifiers() & ACC_STATIC) == 0 && getType().redirect() instanceof InnerClassNode) {
                //                        mv.visitVarInsn(ALOAD, 0);
                //                        for (ClassNode tp = compilerClass ; tp != getType().redirect().getOuterClass(); ) {
                //                            compiler.context.setOuterClassInstanceUsed(tp);
                //                            final ClassNode outerTp = tp.redirect().getOuterClass();
                //                            mv.visitFieldInsn(GETFIELD, BytecodeHelper.getClassInternalName(tp), "this$0", BytecodeHelper.getTypeDescription(outerTp));
                //                            tp = outerTp;
                //                        }
                //                        first = 1;
                //                    }

                for (int i = 0; i != finalArgs.getExpressions().size(); ++i) {
                    BytecodeExpr be = (BytecodeExpr) finalArgs.getExpressions().get(i);
                    be.visit(mv);
                    final ClassNode paramType = constructor1.getParameters()[i + first].getType();
                    final ClassNode type = be.getType();
                    box(type, mv);
                    cast(TypeUtil.wrapSafely(type), TypeUtil.wrapSafely(paramType), mv);
                    unbox(paramType, mv);
                }

                mv.visitMethodInsn(INVOKESPECIAL, classInternalName, "<init>", BytecodeHelper
                        .getMethodDescriptor(ClassHelper.VOID_TYPE, constructor1.getParameters()));
            }
        };
    }

    if (compiler.policy == TypePolicy.STATIC) {
        compiler.addError("Cannot find constructor of " + exp.getType().getName(), exp);
        return null;
    } else
        return createDynamicCall(exp, compiler, newArgs);
}

From source file:org.mbte.groovypp.compiler.UncertainClassNode.java

License:Apache License

public UncertainClassNode(T expression, MethodNode owner, String name) {
    super(owner.getDeclaringClass(), name, Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL, ClassHelper.OBJECT_TYPE,
            ClassNode.EMPTY_ARRAY, null);
    TypeUtil.detachInnerClass(this);
    this.expression = expression;
    setSourcePosition(expression);//from www  .j av  a2  s  . co  m
    expression.setType(this);
    outerMethod = owner;
    setEnclosingMethod(outerMethod);
}

From source file:org.mule.tools.maven.plugin.module.analyze.asm.AccessUtils.java

License:Open Source License

public static boolean isPrivate(int access) {
    return (access & Opcodes.ACC_PRIVATE) == Opcodes.ACC_PRIVATE;
}

From source file:org.openspotlight.bundle.language.java.asm.TypeExtractorVisitor.java

License:Open Source License

/**
 * {@inheritDoc}/*from ww  w  .j a  va  2  s  .  c  o m*/
 */
public void visit(int version, int access, String name, String signature, String superName,
        String[] interfaces) {
    type = new TypeDefinition();

    Pair<String, String> packageAndTypeName = getPackageAndTypeNames(name);
    type.setPackageName(packageAndTypeName.getK1());
    type.setTypeName(packageAndTypeName.getK2());

    if ((access & Opcodes.ACC_INTERFACE) > 0) {
        type.setType(JavaTypes.INTERFACE);
    } else if ((access & Opcodes.ACC_ENUM) > 0) {
        type.setType(JavaTypes.ENUM);
    } else if ((access & Opcodes.ACC_ANNOTATION) > 0) {
        type.setType(JavaTypes.ANNOTATION);
    } else {
        type.setType(JavaTypes.CLASS);
    }
    type.setAccess(access);

    if ((access & Opcodes.ACC_PRIVATE) > 0) {
        type.setPrivate(true);
    }

    if (superName != null) {
        Pair<String, String> superPackageAndTypeName = getPackageAndTypeNames(superName);
        SimpleTypeReference superType = new SimpleTypeReference(superPackageAndTypeName.getK1(),
                superPackageAndTypeName.getK2());
        type.setExtendsDef(superType);
    }

    for (String interfaceName : interfaces) {
        Pair<String, String> interfacePackageAndTypeName = getPackageAndTypeNames(interfaceName);
        SimpleTypeReference interfaceType = new SimpleTypeReference(interfacePackageAndTypeName.getK1(),
                interfacePackageAndTypeName.getK2());
        type.getImplementsDef().add(interfaceType);
    }
}

From source file:org.openspotlight.bundle.language.java.asm.TypeExtractorVisitor.java

License:Open Source License

/**
 * {@inheritDoc}/*w  ww  .  j  av a  2 s .com*/
 */
public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
    ASMParser asmParser = new ASMParser(desc);

    FieldDeclaration field = new FieldDeclaration();
    field.setName(name);
    field.setType(asmParser.type());
    field.setAccess(access);

    if ((access & Opcodes.ACC_PRIVATE) > 0) {
        field.setPrivate(true);
    }

    type.getFields().add(field);

    return null;
}

From source file:org.openspotlight.bundle.language.java.asm.TypeExtractorVisitor.java

License:Open Source License

/**
 * {@inheritDoc}/*from   www .  ja va  2  s  .c  o  m*/
 */
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
    if (name.equals("<clinit>")) {
        return null;
    }

    ASMParser asmParser = new ASMParser(desc);

    MethodDeclaration methodDeclaration = new MethodDeclaration();
    if (name.equals("<init>")) {
        methodDeclaration.setConstructor(true);
        methodDeclaration.setName(type.getTypeName());
    } else {
        methodDeclaration.setName(name);
    }

    methodDeclaration = asmParser.method(methodDeclaration.getName(), methodDeclaration.isConstructor());

    if (exceptions != null) {
        for (String exceptionName : exceptions) {
            Pair<String, String> exceptionPackageAndTypeName = getPackageAndTypeNames(exceptionName);
            SimpleTypeReference exceptionType = new SimpleTypeReference(exceptionPackageAndTypeName.getK1(),
                    exceptionPackageAndTypeName.getK2());
            methodDeclaration.getThrownExceptions().add(exceptionType);
        }
    }

    methodDeclaration.setAccess(access);
    if ((access & Opcodes.ACC_PRIVATE) > 0) {
        methodDeclaration.setPrivate(true);
    }

    type.getMethods().add(methodDeclaration);

    return null;
}

From source file:org.openspotlight.bundle.language.java.resolver.JavaGraphNodeSupport.java

License:Open Source License

/**
 * Adds the type on current context. This method should be used on current classpath elements only. The types declared outside
 * this classpath should be added with method {@link #addTypeOnAbstractContext(Class, String, String)}.
 * //w  w w  . j  a va 2 s .c o m
 * @param nodeType the node type
 * @param packageName the package name
 * @param nodeName the node name
 * @param access the access
 * @param parentType the parent type, if null will use package as parent
 * @return the t
 * @throws Exception the exception
 */
@SuppressWarnings("unchecked")
public <T extends JavaType> T addTypeOnCurrentContext(final Class<T> nodeType, final String packageName,
        final String nodeName, final int access, final Node parentType) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug(" adding type on current context " + packageName + "_" + nodeName + " with parent "
                + (parentType != null ? parentType.getName() : "null"));
    }

    if (usingCache && nodesFromThisContext.containsKey(packageName + nodeName)) {
        return (T) nodesFromThisContext.get(packageName + nodeName);
    }
    if (JavaTypePrimitive.class.equals(nodeType)) {
        final T newType = abstractContextRootNode.addChildNode(nodeType, nodeName);
        newType.setSimpleName(nodeName);
        newType.setQualifiedName(nodeName);
        return newType;
    }
    final JavaPackage newPackage = currentContextRootNode.addChildNode(JavaPackage.class, packageName);
    T newType = null;

    if (parentType != null) {
        newType = parentType.addChildNode(nodeType, nodeName);
    } else {
        newType = newPackage.addChildNode(nodeType, nodeName);
    }

    newType.setSimpleName(nodeName);
    newType.setQualifiedName(Strings.tryToRemoveBegginingFrom(JavaConstants.DEFAULT_PACKAGE + ".",
            packageName + "." + nodeName.replaceAll("[$]", ".")));
    session.addLink(PackageType.class, newPackage, newType, false);
    final boolean isPublic = (access & Opcodes.ACC_PUBLIC) != 0;
    final boolean isPrivate = (access & Opcodes.ACC_PRIVATE) != 0;
    final boolean isStatic = (access & Opcodes.ACC_STATIC) != 0;
    final boolean isFinal = (access & Opcodes.ACC_FINAL) != 0;
    final boolean isProtected = (access & Opcodes.ACC_PROTECTED) != 0;
    newType.setPublic(isPublic);
    newType.setPrivate(isPrivate);
    newType.setStatic(isStatic);
    newType.setFinal(isFinal);
    newType.setProtected(isProtected);

    final JavaPackage newAbstractPackage = abstractContextRootNode.addChildNode(JavaPackage.class, packageName);
    final JavaType newAbstractType = newAbstractPackage.addChildNode(JavaType.class, nodeName);
    newAbstractType.setQualifiedName(Strings.tryToRemoveBegginingFrom(JavaConstants.DEFAULT_PACKAGE + ".",
            packageName + "." + nodeName.replaceAll("[$]", ".")));
    newAbstractType.setSimpleName(nodeName);

    session.addLink(PackageType.class, newPackage, newType, false);
    session.addLink(AbstractTypeBind.class, newAbstractType, newType, false);
    nodesFromThisContext.put(packageName + nodeName, newType);
    if (logger.isInfoEnabled()) {
        logger.info("added class " + nodeType.getSimpleName() + " " + packageName + "." + nodeName);
    }
    return newType;
}