Monday, November 3, 2014

Java assign pro



How to assign default values to custom annotations

package com.java2novice.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
Retention(RetentionPolicy.Runtime)
interface MyAnnot
{
    String key() default "site";
    String value() default "java2novice.com";
}
public class MyAnnotDefaultValues
{
   MyAnnot()
    public void myAnnotationTestMethod()
{
    try
    {
            Class MyAnnotDefaultValues> cls = this.getClass();
            Method mth = cls.getMethod("myAnnotationTestMethod");
            MyAnnot myAnno = mth.getAnnotation(MyAnnot.class);
            System.out.println("key: "+myAnno.key());
            System.out.println("value: "+myAnno.value());
        }
         catch (SecurityException e)
          {
            e.printStackTrace();
          }
         catch (NoSuchMethodException e)
         {
            e.printStackTrace();
        }
    }
   public static void main(String a[])
  {
        MyAnnotDefaultValues mat = new MyAnnotDefaultValues();
        mat.myAnnotationTestMethod();
    }
}

What is marker annotation and how to process it at runtime

package com.java2novice.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
Retention(RetentionPolicy.Runtime)
interface MyMarkerAnnot{}
public class MyMarkerAnnotation
{
   MyMarkerAnnot
    public void myAnnotationTestMethod()
{
       try
     {
            Class MyMarkerAnnotation> cls = this.getClass();
            Method mth = cls.getMethod("myAnnotationTestMethod");
            if(mth.isAnnotationPresent(MyMarkerAnnot.class)){
                System.out.println("Hey... marker annotation is present.");
            }
            else
         {
                System.out.println("Marker annotation is not present.");
            }
        }
         catch (SecurityException e)
        {
            e.printStackTrace();
        }
        catch (NoSuchMethodException e)
        {
               e.printStackTrace();
        }
    }
    public static void main(String a[])
    {
        MyMarkerAnnotation mat = new MyMarkerAnnotation();
        mat.myAnnotationTestMethod();
    }
}

Built-in Java Annotations

package com.java2novice.annotations;
public class MyDeprecatedExmp
{
 public void showDeprecatedMessage()
{
        System.out.println("This method is marked as deprecated");
  }
 public static void main(String a[])
{
        MyDeprecatedExmp mde = new MyDeprecatedExmp();
        mde.showDeprecatedMessage();
    }
}

Built-in Java Annotations

package com.java2novice.annotations;
public class Animal
{
public void makeSound()
{
      }
}

class Cat extends Animal
{
 public void makeSound()
 {
        System.out.println("myyyyyaaawwwwww");
    }
}

No comments:

Post a Comment