Sweet.apex

  • Docs
  • Tutorials
Docs Menu
  • Sweet.apex Core
    • Transpilation
    • Grammar
    • Command
    • Config
  • Features
    • Action
    • Apex Doc
    • Array Creation
    • Aspect
    • Cast
    • Default Value
    • Enum
    • File
    • Function
    • Identity
    • Injection
    • Lambda
    • Log
    • Mod
    • Not Null
    • Operator
    • Optional
    • Reflection
    • Rethrow
    • Switch
    • Template String
    • Template
    • Script
    • Tagged String
    • Annotation
    • Nullable
    • Var
    • Val
    • Map Access
    • Constructor
    • Transaction
    • Destructure
    • Import Static
    • Pipeline
    • Varargs
    • Patch
    • Import As
  • Plugin Development
    • Feature
    • Test Case

Annotation Guide

Annotation

Feature Overview

This feature adds support for custom annotation on classes.

Prerequisite

None

Sweet Apex Example

@MyAnnotation(name='Test')
public class AnnotationDemo {
    public @interface MyAnnotation {
        public String name();

        public Integer number() default 10;
    }
}

Transpiled Apex

public class AnnotationDemo {
    public class MyAnnotation {
        private String m_name;
        private Integer m_number = 10;
        public MyAnnotation name(String m_name) {
            this.m_name = m_name;
            return this;
        }
        public String name() {
            return this.m_name;
        }
        public MyAnnotation number(Integer m_number) {
            this.m_number = m_number;
            return this;
        }
        public Integer number() {
            return this.m_number;
        }
    }
}

Sweet Annotations

public class SweetAnnotations implements Sweet.Annotations {
    private final Map> annotations = new Map>();

    public List getAnnotations(String name) {
        List aList = annotations.get(name);
        return aList == null ? new List() : aList;
    }

    public Object getAnnotation(String name) {
        List aList = getAnnotations(name);
        return aList.isEmpty() ? null : aList.get(0);
    }

    private void registerAnnotation(String targetName, Object annotation) {
        List aList = annotations.get(targetName);
        if(aList == null) {
            aList = new List();
        }
        aList.add(annotation);
        annotations.put(targetName, aList);
    }

    {
        registerAnnotation(AnnotationDemo.class.getName(), new AnnotationDemo.MyAnnotation().name('Test'));
    }
}

Usage

Define custom annotations.

public @interface MyAnnotation {
    public String name();

    public Integer number() default 10;
}

Apply custom annotations on classes.

@MyAnnotation(name='Test')
public class AnnotationDemo {
}

Retrieve annotation information from the instance of the class.

AnnotationDemo demo = new AnnotationDemo();
AnnotationDemo.MyAnnotation myAnn = (AnnotationDemo.MyAnnotation)Sweet.getAnnotation(demo);
System.debug(myAnn.name());

Contribute on Github! Edit this section.