Use of annotations and enumerations in Annotation & Enum:java __java

Source: Internet
Author: User
Tags pear reflection

Java has launched a lot of new things from 5.0, which includes two great sharp objects, as shown in the title. Now let's start with a separate introduction:

"Annotation"

Annotations used to add additional explanatory information to some information, such as metadata concepts, used to describe data. This is useful when designing a basic framework, where you can define annotations that allow application-level programmers to embed and run their own code within your framework. When there is no annotation, the framework usually requires the application-tier developer to write a profile, and with this, developers can write code directly with annotations, such as Spring,hibernate. Let's go straight to the example:

Package cn.test;

Import Java.lang.annotation.ElementType;
Import java.lang.annotation.Retention;
Import Java.lang.annotation.RetentionPolicy;
Import Java.lang.annotation.Target;

@Retention (retentionpolicy.runtime)
@Target (elementtype.field) public
@interface Serviceimpl {
	
	public String value ();
}

Define annotations by keyword @interface, and custom annotations are inherited from Java.lang.annotation.Annotation by default. The @retention @Target is also two annotations, which are provided by Java itself to annotate our own annotations (good around the mouth), is the meta annotation. The @Retention represents the scope of the annotation, which indicates that the annotation exists in the runtime, which is the byte code. Retentionpolicy also has a value of source, indicating that the annotation will only exist in the source code for the compiler to use, the most typical is the annotation @override, this overwrite annotation only exists in the source code, for the compiler to use. @Target annotation, indicating that the use of the annotation object, we set here as a member variable, this annotation can only note the member variable, ElementType there are many other values, are as the name suggests.

Only "interface" can be defined in the note, which is used to set values and values in the annotation. As follows, we use the above annotation:

Order service Object
@ServiceImpl (value= "Cn.test.OrderSeviceImpl")
private OrderService OrderService;

Here's a tip, if you use an interface named value only in your annotations, you can pass the value directly without specifying the name:

Order service object
@ServiceImpl ("Cn.test.OrderSeviceImpl")
private OrderService OrderService;

This approach is limited to situations where only one value () interface is used in the annotation, and when there are multiple interfaces in the annotation, all interfaces must be assigned a value in the form of a specified name and separated by commas. As we define and use annotations in the actual business code, how does this annotation work? Annotations are used in conjunction with reflection, and we look at examples:

Package cn.test;
Import Java.lang.reflect.Field;
Import java.lang.reflect.InvocationTargetException;

Import Java.lang.reflect.Method;
	
	public class Testannotation {//Order service object @ServiceImpl ("Cn.test.OrderSeviceImpl") private OrderService OrderService;
	Public OrderService Getorderservice () {return orderservice;
	public void Setorderservice (OrderService orderservice) {this.orderservice = OrderService;
		public static void Main (string[] args) {testannotation ta = getinstance ();
	Ta.getorderservice (). PlaceOrder ("Apple");
		public static Testannotation getinstance () {testannotation ta = new Testannotation ();
		field[] fields = Ta.getclass (). Getdeclaredfields (); if (null!= fields && fields.length > 0) {for (Field field:fields) {if (Field.isannotationpresen
					T (Serviceimpl.class)) {String serviceimplclassname = field.getannotation (Serviceimpl.class). Value ();
					String fieldName = Field.getname (); String FieldsetmetHodname = "Set" + string.valueof (Fieldname.charat (0)). toUpperCase ();
					if (Fieldname.length () > 1) {fieldsetmethodname + = fieldname.substring (1);
					} field.gettype ();
						try {Method Fieldsetmethod = Ta.getclass (). GetMethod (Fieldsetmethodname, New Class[]{field.gettype ());
					Fieldsetmethod.invoke (TA, New Object[]{class.forname (Serviceimplclassname). newinstance ()});
					catch (SecurityException e) {e.printstacktrace ();
					catch (Nosuchmethodexception e) {e.printstacktrace ();
					catch (IllegalArgumentException e) {e.printstacktrace ();
					catch (Illegalaccessexception e) {e.printstacktrace ();
					catch (InvocationTargetException e) {e.printstacktrace ();
					catch (Instantiationexception e) {e.printstacktrace ();
					catch (ClassNotFoundException e) {e.printstacktrace ();
	}} return TA;
 }

}


In the example above, we registered an implementation object of the order service with a reference to the Order service interface type through annotations and successfully invoked the corresponding method of the order service interface. With this piece of code, application layer developers can easily inject a service implementation into the service interface, which is a classic application of annotation and reflection.

"Enum"

In Java coding, you often need to define a series of constants of the same type meaning, we look at an "old fruit shop" application, the fruit shop object according to the name of the incoming fruit return price, if there is no unit price, then throw an exception:

Package cn.test;

public class Oldfruitshop {public
	
	static final String Apple = "Apple";
	public static final String pear = "pear";
	public static final String orange = "orange";
	public static final Double apple_price = 6.5;
	public static final Double pear_price = 5.5;
	public static final Double orange_price = 4.5;
	
	Public double GetPrice (String fruit) {
		
		if (apple.equals (fruit)) {return
			
			apple_price;
		} else if (pear.equals (fruit)) {return
			
			pear_price;
		} else if (orange.equals (fruit)) {return
			
			orange_price;
		} else{
			
			throw new IllegalArgumentException ("fruit" + fruit + "is not in the range of sale.") ");
		}
		
		
	}

}


This example can work well, but its existence is a bad place, the user must choose to run the program, only to know whether the fruit in the sale range (through the form of throwing exceptions). When users use this object interface, the user can pass in any fruit, and the program can be compiled. There is no problem with this design, but the usability is poor, and by making the fruit an enumeration, we can avoid this problem:

The following fruit are custom enumerations, and custom enumerations inherit from Java.lang.Enum classes by default:

Package cn.test;

public enum Fruit {
	
	APPLE, PEAR, ORANGE;
}

Package cn.test;

public class Newfruitshop {public
	
	static final double apple_price = 6.5;
	public static final Double pear_price = 5.5;
	public static final Double orange_price = 4.5;
	
	Public double GetPrice (Fruit Fruit) {
		
		if (null = = Fruit) {
			
			throw new IllegalArgumentException ("Please pass in the correct fruit.") ");
		}
		if (fruit.apple = = Fruit) {return
			
			apple_price;
		} else if (fruit.pear = = Fruit) {return
			
			pear_price;
		} else if (Fruit.orange = = Fruit) {return
			
			orange_price;
		}
		
		return 0;
	}

}



By defining the fruit enumeration, the "New Fruit Shop" interface method can only accept the fruit enumeration type, and the user cannot pass the parameters randomly. If passed randomly, the compiler cannot pass. So when you write code, you know what fruit stores sell. By enumerating, we move the point of occurrence of an exception from the runtime to the compile period (which cannot be controlled for an incoming null parameter). The best practice for programming is to make the exception appear as early as possible. This is the credit of the enumeration. In an improved version of the above example, the fruit unit price is also integrated into the fruit enumeration definition, so that the code is better encapsulated:

Package cn.test;

The public enum Fruit {
	
	/**
	 * These constants are the only few objects of this enumeration class.
	 */
	APPLE (6.5), PEAR (5.5), ORANGE (4.5);
	
	private double price;
	 the/** * Enum type does not support external creation of objects, so its constructors must be private.
	 * @param price
	/Private Fruit (double price) {
		
		This.price = Price;
	}
	
	Public double GetPrice () {return price
		;
	}
	
	public void Setprice (double price) {
		This.price = Price;
	}
	
}
Package cn.test;

public class Newfruitshop {public
	
	double getprice (Fruit Fruit) {
		
		if (null = = Fruit) {
			
			throw new IllegalArgumentException ("Please pass in the correct fruit.") ");
		}
		
		return Fruit.getprice ();
	}


From the enumeration definition, we can see that the enumeration's constructors must be private, because the enumeration class contents must first define an instance of the enumeration, which is the only few instances of this enumeration type, and the enumeration does not support external creation of instances.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.