Making a Custom Annotation similar to @Deprecated

I want to make an annotation for a method (and annotation processor) that at compile-time will throw a custom warning/error if a user ever uses the annotated method during compile time.
Currently I have a way to throw a warning/error at the declaration of the method, but not at the method's use.
I'd like it to only throw an error at a usage of the method. I'm thinking i may have to do some tricky stuff with reflection, but I'd like to know if annotations already have some way to do this (I can't find any after several searches).
I'm hoping that it is easy, since @Deprecated already does a similar thing (errors at use, not declaration)
Here's my code at the moment (again, it causes errors for the declarations of the methods, not the uses).
A) The actual annotation
package unsupported;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.SOURCE)
@Target({ ElementType.METHOD})
public @interface Unsupported {
}B) The annotation processor
package unsupported;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic.Kind;
@SupportedAnnotationTypes("unsupported.Unsupported")
public class UnsupportedProcessor extends AbstractProcessor {
    private ProcessingEnvironment env;
    @Override
    public synchronized void init(ProcessingEnvironment procEnv) {
        this.env = procEnv;
    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        if (!roundEnv.processingOver()) {
            for (TypeElement myTypeElement : annotations) {
                final Set< ? extends Element> elements = roundEnv.getElementsAnnotatedWith(myTypeElement);
                for (Element elt : elements) {
                    env.getMessager().printMessage(Kind.ERROR,
                            String.format("%s : The Following Element is Unsupported: %s"
                            + "\nThe Compiler will now exit. \n\n", roundEnv.getRootElements(), elt),
                            myTypeElement);
        return true;
}I then compile these 2 files into a JAR, along with the folder: "META_INF/services" that has the file: "javax.annotation.processing.Processor", with 1 line of text giving the path to the processor: "unsupported.UnsupportedProcessor" (this lets javac know to use the processor at compile time)
I can then import this jar to my libraries and use the @Unsupported annotation like this:
class OtherClass1
   @Unsupported
   public void unsupportedmethod()
      System.out.println("hi1") ;
}Then, when compiling the above code i get this:
error: [OtherClass1] : The Following Element is Unsupported: unsupportedmethod()
The Compiler will now exit. Any ideas on how i can modify this to only throw an error when the method is used?
Thanks,
- JT
Edited by: 00jt on Jul 6, 2011 7:57 AM

Hi,
I read your blog. The solution that you provided in the blog is creating new Assignment Block and integrate it in BT application on the UI level. The data is populated from the UI by calling Function Module and fill the value context node.
This will not propagate to GenIL, therefore you will not see any thing on GenIL layer, because there is no integration on GenIL layer.
The approach needs to be the other way around. Your approach is make something available in UI and you want to propagate it to backend(GenIL). The value node that you created in the UI is not dependent object. It is only a context node which is only available in UI. The right approach is you make the dependent object on the backend(GenIL) and than you propagate the dependent object to the UI.
You can try transaction EEWB to create custom table for BT application and this will generate for you also the dependent object on the GenIL layer. This solution provided by EEWB has also a generic assignment block that displays the generated dependent object and show it in BT overview page. To see the generic assignment block from BT you can open the component BT_GEN_EXT.
Regards,
Steve

Similar Messages

  • Simple example of a custom annotation    for log

    Please help me write me my custom annotations. I like to use them to provide log ,security etc . I did not find articles where I can write my annotation to change the behaviour. Suppoe I decare annotation on a method , I want jvm to call code in my annotation where I can control the behaviour of the method similar to aop stuff ,
    here is what i need
    MyClass {
      @MyCustomAnnotation
       void myMethod(){
    }now I want MyCustomAnnotation to log that this method is begin called can I do this ?

    I can think of only one way to do something like this, and it's messy:
    Let's say your code looks like this:
    public class MyClass
        @MyLogging
        public void myMethod(String arg)
    }Have your @MyLogging annotation processing generate a new Class source that extends your original class and overrides the methods that you've annotated with code that looks something like this:
    public class MyClassGenerated extends MyClass
       Log log = ... // create a logger
        @Override
        public void myMethod(String arg)
            log.info("myMethod called");
            super.myMethod(arg);
    }Now you'll have to change your code to use MyClassGenerated instead of MyClass, which presents its own problems... you may be able to add in some kind of factory mechanism or something to make that work easier.

  • Custom Annotation :: inject object at runtime

    I would like develop a custom annotation to inject object at runtime. The annotation will work as follows
    1. develop ValidatorClass annotation on type.
    2. If annotated on a type object will be created at runtime and injected to the object. e.g. in class A it will inject validatorimpl object to vald object/
    Please let me know how to implement that.
    package com.debopam.validate
    public interface validator{
    public String validate();
    package com.debopam.validate
    public class validatorimpl implements validator{
    public String validate(){
       return "true";
    pckage com.debopam
    public class A{
    @ValidatorClass(name="com.debopam.validate.validatorimpl")
    validator vald;
    }

    yogeshd,
    It might be that the .class file for the annotation that you are compiling against is the one you have given us the source code for above, but when you run the program, the class file for the annotation is not the same, and is one that was compiled before you added the static field.
    This can happen if your classpath is wrong. (and would explain why the problem only occurs sometimes - because it is only failing when the classpath is wrong).
    If you run the following program with the Fully qualified name of your annotation as the argument, and with the same classpath as you run your program, it can tell you where it is finding the annotation class file. Check that this is the same one that you are compiling to.
    class WhereLoaded {
        public static void main(String[] args) {
            Class theClass=null;
            if(args.length > 0) {
                try {
                    theClass=Class.forName(args[0]);
                } catch (Exception e) {
                    e.printStackTrace();
                    theClass=Object.class;
            } else {
                System.out.println(
                    "The first argument should be a fully qualified class name," +
                    " using java.lang.Object instead"
                theClass=Object.class;
            String name=theClass.getName();
            name=name.substring(name.lastIndexOf(".")+1) + ".class";
            System.out.println(name + " loaded from " + theClass.getResource(name));
    }regards
    Bruce

  • PDF Custom Annotations Types?

    Can some kind reader comment and/or point to documentation on PDF's Custom Annotation Types?
    I was first introduced to those by Aandi Inston's reply to my "Click to Dial Plugin" posting.
    Unfortunately, such posting seems to have been pulled (lost?, relocated?, bitbucketed?) from the forum.
    My objective is to programmatically insert several links of different types in my PDF files. I intend to have a type for voice phone numbers, another for fax numbers, and yet another company or client ID, etc.
    The part below refers to a plugin (to be written).
    Later on, when the user clicks on a phone number, a call will be placed, clicks on a fax number will result in the document being faxed, while a click on an ID will result on a database lookup.
    I don't want to go through the hassle of studying the page's geometry to determine whether a phone number is voice or fax. I am just looking for a way to mark the different links, giving each one of them a type, which will be passed to the plugin upon a link being clicked.
    I recall that Aandi's explanation made an exact match for my application, but as I said before, his posting is gone.
    -Ramon

    Perhaps the use Custom Annotation Types (CAT) is an overkill? It seems that when a CAT is defined, an annotation handler has to be registered, and such handler provides the drawing. In my case I don't need any custom drawing. I just need to mark somehow the different links, assigning a type to each.
    Thanks for sharing your expertise, and helping the PDF format to become more useful and widespread...
    -Ramon

  • What has happened to making the customer happy?

    I have 5 months left on my contract (November 2014) and yesterday I dropped my phone and it is completely dead.  I carry insurance on the phone so it can be replaced.  I would prefer to upgrade at this time to a new phone (Samsung Galaxy).  I went into the Verizon store and was told that unless I paid retail I would not be able to get a new phone as I was under contract.  Really?  Can I not extend my contract by another 2 years and get the phone I want now instead of waiting until November?  I told the employee that I would be going to T-Mobile since they are paying EFT's and offering the Galaxy for $0 down.  The monthly payment would be the same as I would get at Verizon.  He said "then that's what you should do".  Again, Really????  I have been with Verizon for more than 10 years!  I would consider myself a good and loyal customer.  What has happened to making the customer happy?  I was more than okay with extending my contract for an additional two years and completing the 5 months I have left.  All I wanted was to purchase a phone at a "customer rate" not a retail rate.  I am now shopping other carriers and plans.  Not the way to do business Verizon!

    You agreed to complete a 24 month contract, you are only 20 months into that contract. The Samsung you're referring to or any phone with T-Mobile won't be free, you will end up paying the full retail price of that phone like you said you did not want to do with Verizon. If you have insurance use it to get your phone replaced and then wait for your upgrade date.

  • Adding link to custom annotation.

    Hi all...
    I am developing a plugin that stamps  custom annotation to a pdf file.
    I would like to add a link to it by adding another annotation of type 'link'  just above it.
    But the link is not working when it is above my custom annotation.
    (When it is not above the custom annotation this URI link is working fine.)
    I also tried with Acrobat 9 Pro's link tool. The link provided by this tool
    is also not working when it is above my custom annotation. Is this a bug in
    Acrobat or due to some reason is this not recognizing by custom annotation?
    But in both above cases the link (made from my plugin and Acrobat's tool) are get
    selected and active temporarily on tab press.
    Please help me to set link annotation on a custom annotation.
    Regards
    Sudhin.
    I

    But when i changed my stamp Subtype to 'Stamp'(Subtype of rubber stamp)
    i could able to add link to my stamp.Then why i couldn't add link to a custom stamp.
    If acrobat could place the link on top of rubber stamp(Subtype :Stamp), can anybody say how they
    implement this. The same implementation may help my custom annotation to add link above it.

  • VCenter 5 Alerts with custom Annotations

    Hello,
    I want to be able to create alerts with the use of SCOM and VCenter's PowerCLI. Has anyone been able to achieve this?
    Essentially I want to tie into VCenter's console, and grab the custom annotations define by the user, and feed the custom annotations back into the SCOM generated alert.
    Suggestions? Thanks.

    Hi,
    You can build a pack that leverages powercli for discovery and monitoring.At least you could use powercli to check for vcenter alerts and bring them to scom.
    Niki Han
    TechNet Community Support

  • Running custom annotations from ant

    I know this may be the wrong forum for such a question but figured someone ,ight have done it b4 and will not mind telling me
    I want to know how to run my custom annotation processor from an ant build script.
    I can run it from commanline but i dont know the ant targets fro doing it

    Vikas:
    Can you help me with this one too.....
    I am trying to add a custom page in iproc. According to the dev guide I should use the same AM that iproc uses. so I used ShoppingAM provided by Oracle. I extended it and created my own Am called DKSearchAM. But when I try to run the page from Jdev I get the following error messages.
    I brought ShoppingAM.xml file from the server and added it to my project and then updated it to create ShoppingAMImpl.java file.
    Please help!!!!!!!!
    I get the following error:
    Project: DKSearchOAProject.jpr
    C:\JDev\jdevhome\jdev\myprojects\oracle\apps\icx\icatalog\shopping\server\ShoppingAMImpl.java
    Error: can't read: C:\JDev\jdevhome\jdev\myprojects\oracle\apps\icx\icatalog\shopping\server\ShoppingAMImpl.java
    C:\JDev\jdevhome\jdev\myprojects\dekalb\oracle\apps\xxdk\search\server\DKSearchAMImpl.java
    Error(2,49): cannot access class oracle.apps.icx.icatalog.shopping.server.ShoppingAMImpl; file oracle\apps\icx\icatalog\shopping\server\ShoppingAMImpl.class not found
    Error(8,37): class ShoppingAMImpl not found in class dekalb.oracle.apps.xxdk.search.server.DKSearchAMImpl

  • Making a customer inactive in R12 Receivables

    I am using R12 and in receivables I am attempting to make customer inactive but cant seem to find how to do it in this form. I can make the account and site inactive but not the customer. I am sure that there is a simple way to do this but the customer form in R12 can be hard to follow at times. Any help would be greatly appreciated. Thanks

    Hi Helios
    Thanks for the info however the note refers to making a customer contact inactive, but does not refer to making the customer itself inactive. Also the AR user guide does not display how to do this either.
    Does anyone else have any idea how to make a customer inactive in the R12 AR customer form?
    Thanks

  • Custom Annotation showing Error: is missing clinit

    Hi!
    I have created some custom annotations for use in my project. Sometimes they show error: is missing <clinit> and sometimes they don't. I'm confused. If I create a jar and use that jar in another project this error appears at compiletime .
    Here is the source of one of my custom annotations....
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    * User: yogeshd
    * Date: Mar 30, 2007
    * Time: 10:54:31 AM
    @Constraint
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.FIELD)
    public @interface ConstraintMaxIntValue {
    public Validator validator = new MaxIntValidator();
    int value() default 0;
    The strange thing is that this error doesnot appears all the time...
    If anyone can explain the reason I will be enlightened. ;) thnx.

    yogeshd,
    It might be that the .class file for the annotation that you are compiling against is the one you have given us the source code for above, but when you run the program, the class file for the annotation is not the same, and is one that was compiled before you added the static field.
    This can happen if your classpath is wrong. (and would explain why the problem only occurs sometimes - because it is only failing when the classpath is wrong).
    If you run the following program with the Fully qualified name of your annotation as the argument, and with the same classpath as you run your program, it can tell you where it is finding the annotation class file. Check that this is the same one that you are compiling to.
    class WhereLoaded {
        public static void main(String[] args) {
            Class theClass=null;
            if(args.length > 0) {
                try {
                    theClass=Class.forName(args[0]);
                } catch (Exception e) {
                    e.printStackTrace();
                    theClass=Object.class;
            } else {
                System.out.println(
                    "The first argument should be a fully qualified class name," +
                    " using java.lang.Object instead"
                theClass=Object.class;
            String name=theClass.getName();
            name=name.substring(name.lastIndexOf(".")+1) + ".class";
            System.out.println(name + " loaded from " + theClass.getResource(name));
    }regards
    Bruce

  • Creating custom annotations (Singleton)

    Hi,
    Am bit out date of java so that's why I am posting this;
    Actually I want to write my custom annotation of Singleton like,
    *@Singleton*
    Class Spooler {
    so now when this annotation is applied on any class will become a singleton by automatically providing the Spooler::getInstence() method (donno may be at runtime or compiletime)
    and if user tries to declare the public constructor then there should be a compile time error that @Singleton is applied so the constructor should not be public.
    Am I asking a correct thing regarding the annotations or am already lost due to being outdate
    thanks in advance
    Edited by: user10657941 on Jun 15, 2011 12:18 AM

    What would be the advantage over using the simpler enum singleton?
    enum Spooler {
        INSTANCE;
    }An enum type automatically ensures that only the instances listed are created.

  • HandlerChain annotation name attribute deprecated.

    Hi All,
    I am using @HandlerChain(file="HandlerConfig.xml") annotation to configure a SOAPMessageHandler in my Impl file. This annotation contains a deprecated "name" attribute. When I am not specifying "name" attribute in the annotation, JWSC task is throwing "Null Pointer Exception" while creating the war of the service. This is probably because the HandlerConfig.xml contains handler-chain-name element and the annotation doesn't contain "name" attribute. When I am specifying name attribute in the annotation everything is fine. Please help me in resolving the problem without "name" attribute.
    This is the code I am having:
    SubmitApplicationServiceImpl.java:
    package com.project.webservices.submitappservice;
    import javax.jws.WebService;
    import weblogic.jws.WLHttpTransport;
    import javax.jws.HandlerChain;
    **@HandlerChain(file = “SubmitAppHandlerChain.xml”)**
    @WebService(serviceName = "SubmitApplicationService", targetNamespace = "http://project.com/ SubmitApplicationService", endpointInterface = "com.project.webservices.submitappservice.SubmitApplicationServiceSoap")
    @WLHttpTransport(contextPath = "SubmitApplicationService", serviceUri = "SubmitApplicationService", portName = "SubmitApplicationServiceSoapSoapPort")
    public class SubmitApplicationServiceSoapImpl implements
              SubmitApplicationServiceSoap {
         public SubmitApplicationRes submitApplication(
                   SubmitApplicationReq submitApplicationRq) {
    // Our business logic here.
              return submitApplicationRes;
    This is my handler configuration file in the same package:
    SubmitAppHandlerChain.xml:
    <?xml version='1.0' encoding='UTF-8'?>
    <jwshc:handler-config xmlns:jwshc="http://www.bea.com/xml/ns/jws"
    xmlns="http://java.sun.com/xml/ns/j2ee" >
    <jwshc:handler-chain>
    <jwshc:handler-chain-name>HandlerChain</jwshc:handler-chain-name>
    <jwshc:handler>
    <handler-name>AppServiceHandler</handler-name>
    <handler-class>com.project.webservices.submitappservice.AppServiceHandler</handler-class>
    </jwshc:handler>
    </jwshc:handler-chain>
    </jwshc:handler-config>
    This is the build target that creates war of the service:
    <taskdef name="jwsc"
              classname="weblogic.wsee.tools.anttasks.JwscTask"
              classpathref="compile.classpath" />          
    <target name="create-appservice-war>
    <jwsc srcdir="${basedir}/project/src" destdir="${basedir}/projectEAR/build">
                   <jws file="com/project/webservices/submitappservice/SubmitApplicationServiceSoapImpl.java"/>
                   <classpath refid="jwsant.classpath" />
              </jwsc>               
    </target>
    Thanks,
    Satya

    The default value of the name() attribute for field-based Java EE environment annotations is
    <fully-qualified-name-of-declaring-class>/<field-name>. It's a bit ugly, but at least it's guaranteed
    to be unique :-)
    --ken                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Making JTree custom renderer panel scalable

    Hi, everyone. I have made custom TreeCellRenderer which extends JPanel. Panel's background is in different color than JTree's backgound. I need to get my panel rendering the nodes to fill the whole space JTree has in it's parent panel horizontally. For now I have put static width to nodes and it looks fine, but it's not scalable. If I don't put any sizes the panel takes only the size it needs in cell and the outfit is crappy because of panel's different bgcolor. Is there any easy way to make rendering panel use the width which JTree has in it's container. I have implemented getPreferredSize() method in custom TreeCellRenderer and now it returns the static width and height of the rendering panel. Do I have to get JTrees container panel's width every time and pass it to renderer and get size somehow from there or is there some easier way.
    -e

    Yes, there is a reason. Different levels of nodes contain different components. Example main level nodes have print and save buttons on the most right of the panel. Only leafs have same bgcolor as the tree has and those are already now scalable, because size is not set for them.

  • Making some Custom Column Renderers for a JTable

    Hello People
    I've been playing around with a JTable by following the tutorial "How to Use Tables". (I am using netBeans 4.1 to "sculpt" my swing objects onto the nice palette in the IDE. I don't know if this has anything to do with the errors but, it seems like netBeans requires some Gui components be initialized via this abovementioned "palette")
    I believe that I need to somehow tell the JTable about what kinds of objects are in it so that it can render itself properly. I have a table set up with some default values in it
    ->Strings both Editable and Not-Editable
    -> Integers both Editable and Not-Editable
    -> Boolean rendered as a check box Editable
    So upon startup, my progarm renders the table correctly. I have a button to clear all of the elements in the table, which works fine. It is only when I switch to another window, then switch back to an empty table ... the JTable needs to redraw itself. This is when I'm getting the error:
    java.lang.NullPointerException
            at ElementHelp.PrimitiveManager$MyVectorTableModel.getColumnClass(PrimitiveManager.java:93)
            at javax.swing.JTable.getColumnClass(JTable.java:1752)
            at javax.swing.JTable.getCellRenderer(JTable.java:3700)
            at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:1148)
            at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:1051)
            at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:974)
            at javax.swing.plaf.ComponentUI.update(ComponentUI.java:142)
            at javax.swing.JComponent.paintComponent(JComponent.java:541)
            at javax.swing.JComponent.paint(JComponent.java:808)
    ...blah blah more exception stack.....
           I think that because there are no elements in the table that the call to "getClass" for an element in the table returns a NullPointerException. I think I can avoid this via telling the JTable about the types of objects each column will contain. The tutorial suggests one of two solutions: (neither of which I can get to work)
    1) Use a class that extends the DefaultTableCellRenderer
    2) I should write somthing that ...extends JLabel and implements TableCellRenderer.... such as the tutorials ColorRenderer example. Which solution should I work out if I want my table to add/delete rows and be able to have a few cells edited. (It will never be restructured .. the column types won't change)
    Also, I've created my own TableModel for it ... a class that extends AbstractTableModel ... (although not declaired, it also implemnts/overwrites functions from the TableModel interface)
    Any suggestions on avoiding the abovementioned error?
    thanks and happy holidays to everyone

    I think that because there are no elements in the table that the call to "getClass" for an element in the table returns a NullPointerExceptionWell, if you have no data in the table then your TableModel should be returning "0" for the number of rows in the table and it won't be a problem.
    Also, I've created my own TableModel for it ... Why? Use the DefaultTableModel it supports String, Integers and Booleans without any need for custom coding.

  • Help on Custom Annotation Mapping between @CustomAnno and ResultSet Mapping

    Hi,
    I am working on a DAO which has getter and setter methods and annotation of the Database Table Column Name.
    Class UserDao {
    @CustomAnnotation(value="FIRST_NAME")
    String firstName
    CREATE TABLE USER(
    FIRST_NAME VARCHAR(30)
    Question
    1. I am planning to create a generic implementation where the when i give the Result Set and Dao name it should fill the Dao automatically. I was using Reflection but was wondering is any better way to handel this?
    I am using JDK 1.6 and i am not sure why JDBC 4.0 (which says its part of JDK 1.6) has no DataSet api's.
    Any ideas are very helpful.
    Thanks..,
    User
    Edited by: user.java on Feb 18, 2010 6:56 PM

    Far as I know annotations do not magically produce code. You must use them in something else which understands the annotations and the intent. I didn't see you mentioning anything like that. I am rather certain that there are existing consumers (of annotations) that do that and you can create your own.
    Also, again as far as I know, you don't really have a "DAO" there, but rather a DTO.

Maybe you are looking for

  • How do you sync an iPhone with a new computer?

    I know this question has been posted on this forum countless times, but none of the responses seemed to help me. I need a simple and clear answer on how to sync my iPhone to a new computer. I used to sync my iPhone with a Mac, but I got a new laptop

  • How can I download Acrobat X Professional?

    I have a license to Adobe Acrobat X Professional but my computer crashed and I need to download.  Any help to a link for that download would be appreciated.   Previously, a person asked the same question on this forum and was directed to the followin

  • How do I sort the order of bookmark folders themselves?

    I see plenty of instructions on how to sort marks ''within'' a folder, but I'm unable to find how to sort the order of the bookmark folders themselves. Ideally, I'd like to alphabetize them, but on occasion I might prefer sorting by the date the fold

  • How to lookup what datatype JSF tag component requires?

    Kinda beginner question following on my part and not sure I'm asking this in the correct web-page speak? I just happen to know if I have a tag such as <af:tree>, I know its value attribute requires an instance of oracle.adf.view.faces.model.TreeModel

  • Re: Sap hcm certification information

    Hi Expert, As i am writing the sap hcm associate level certification exam next month just i wanted to know if i am unable to clear the exam can i eligible for second time and is their any remark like this will come in the certification for second att