New features of JDK1.5: JavaBean, annotation class, class loader

Source: Internet
Author: User

On the Java foundation of the article, I think it can also be written in my other blog, is definitely original, and now share to everyone out.

--------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------



First, JavaBean
I. Overview

JavaBean is a Java component that conforms to a specification, that is, a Java class.
It must meet the following specifications:

1) must have a default constructor for a 0 parameter

2) The Get and set methods must be used, and the fields of the class must be accessed through the get and set methods.

(Get method no parameter, set method has parameters)

For example, one of the following classes is a JavaBean class

Package cn.jinfulin.day2.javabean;/** * @author Jinfoling * */public class UserBean {private string name;private string password ;p ublic String getName () {return name;} public void SetName (String name) {this.name = name;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;}}



Second, introspection

So how does the JavaBean class work, and here's a look at the Java introspection mechanism.

The JDK provides an API for doing something about JavaBean, which is introspection.

Introspection (introspector) is a default processing method of the Java language for Bean class properties and events.

For example, there is a property name in Class A, so we can get its value by Getname,setname or set a new value.


Invoking the JavaBean sample through introspection


1, through the PropertyDescriptor call, relatively simple some </p><p>propertydescriptor describe JavaBean class, through a pair of memory method to export a property.


Package Cn.jinfulin.day2.javabean;import Java.beans.introspectionexception;import Java.beans.PropertyDescriptor; Import Java.lang.reflect.invocationtargetexception;import java.lang.reflect.method;/** * @author 金福林 * */public class Introbean {public static void main (string[] args) throws exception{string propertyname = "name"; Object user = new Userbea n (); Setmethod (PropertyName, user); GetMethod (PropertyName, user);} private static void GetMethod (String propertyname, Object user) throws Introspectionexception, Illegalaccessexception, IllegalArgumentException, invocationtargetexception {propertydescriptor pd = new PropertyDescriptor (PropertyName, User.getclass ()); Method methodgetname = Pd.getreadmethod (); Methodgetname.invoke (user, null);} private static void Setmethod (String propertyname, Object obj) throws Exception{//propertydescriptor describes the Java Bean through a pair of memory-side A property of the export method. PropertyDescriptor PD = new PropertyDescriptor (Propertyname,obj.getclass ()); Method methodsetname = Pd.getwritemethod (); MethodseTname.invoke (obj, "Jinfulin");}} 

2, through the Introspector class call, relatively complex some

as follows, the Setmethod method of rewriting

private static Object Setmethod (String PropertyName, Object obj) throws Exception{beaninfo bean = Introspector.getbeaninf O (Obj.getclass ()); propertydescriptor[] pds = Bean.getpropertydescriptors (), Object returnvalue = null;for (PropertyDescriptor pd:pds) {if ( Pd.getname () ==propertyname) {Method methodgetx = Pd.getreadmethod (); returnvalue = Methodgetx.invoke (obj);}} return returnvalue;}


III. beanuntils Toolkit 1, overview

The Beanuntils Toolkit is a tool class for JavaBean operation properties and is widely used.

It is not developed by Sun but is a third-party toolkit developed by Apache and needs to be downloaded separately for use.

The method of importing the jar package is relatively simple, not in detail, but to remember not only to import the Beanuntils Toolkit, but also to import the logging package

public static void Main (string[] args) throws Exception{userbean bean = new UserBean (); Beanutils.setproperty (Bean, "name", "N"),//set method Beanutils.getproperty (Bean, "name");//get method}
Call JavaBean's set and get method at this time, all of a sudden become only 2 lines of code, feel good bang.


2, for the property in JavaBean is the operation of the object

If my JavaBean class returns an object, this object also has get and set methods (such as the Date object has gettime () and the SetTime () method)

Like what

Private date Birthday;public Date Getbirthday () {return birthday;} public void Setbirthday (Date birthday) {this.birthday = birthday;}

Then the call can be called at a multiple level

Beanutils.setproperty (Bean, "birthday.time", 12);


3,propertyutils Tool Class

Propertyutils Tool class usage is basically the same as beanutils.

Difference:
1) Beanutils Converts the type of the JavaBean property, as if the property itself is an integer and is converted to string.
2) The Propertyutils is operated in the type of the property itself.



Second, the annotation class


One, overview

Annotations can be used to create documents, track dependencies in code, and even perform basic compile-time checks.

adding annotations in a program is tantamount to marking a program with a certain mark, without adding a tag.



Two, the Lang packet three commonly used annotation class

1,override----Represents a method declaration that intends to override another method declaration in a superclass.

2,deprecated----out of date

3,suppresswarnings----Ignore warning messages (do not prompt for outdated information)


Iii. calls reflected in annotations

public static void Main (string[] args) {//returns TRUE if annotations of the specified type exist on this element, otherwise false. if (AnnotationTest.class.isAnnotationPresent (Ianncation.class)) {//If there is a comment of the specified type for the element, the comments are returned, otherwise null is returned. Ianncation anno = AnnotationTest.class.getAnnotation (Ianncation.class); System.out.println (anno);}}

Iv. Annotations: Annotations

The above example of the reflection of the direct execution is certainly not successful, because we have not written the annotation class, and did not change the contents of the meta-annotations.

Meta-annotations are annotated when defining annotation classes, and meta-annotations typically include two, retention and target.

1,retention

Retention has three kinds of values

Retentionpolicy.source----Java source file period, the compiler will discard comments.

Retentionpolicy.class---The compiler will record annotations in the class file, but the VM does not need to retain annotations at run time. Default

Retentionpolicy.runtime----The compiler will record annotations in the class file, and the VM will retain comments at run time, so it can be read in a reflective manner.


Run-time detection comment @retention (retentionpolicy.runtime) public @interface ianncation {}

2,target

Where to use the annotation class

Elementtype.type------class, interface (including annotation type), or enumeration declaration can use this annotation

This annotation can be used in the Elementtype.method-----method

Elementtype.annotation_type------Annotation Type declaration

CONSTRUCTOR------Construction Method declaration

Field declarations-------fields (including enumeration constants)

local_variable------local variable declarations

Package-------Packages Declaration

PARAMETER--------Parameter Declaration

@Target ({elementtype.type,elementtype.method,elementtype.annotation_type}) public @interface ianncation {}


V. Adding attributes to Annotations

If there is only one property or other property of value name default, you can @ Note name ("attribute value");

If there are multiple or no defaults or need to be re-assigned, the @ Annotation Name (property name = "Property value", ...) )。


The run-time detection comment @retention (retentionpolicy.runtime)//The position where the comment can be placed, which means it can be @target in a method class ({Elementtype.type, Elementtype.method,elementtype.annotation_type}) Public @interface Ianncation {//Add a method to the annotation, the default value is Greenstring color () Default "green";//when there is only the value attribute, the = sign can omit string value () default "defaults";//An array method, if only one value, curly braces can omit int[] arr () default {n}; When invoked such as//@IAnncation (color = "Red", arr = {2,2,3})}

Call

@IAnncation (color = "Red", arr = {2, 2, 3})


Third, class loader


1, overview

The class loader says that the simple thing is to load the tools of the class.

In general, Java virtual machines use Java classes in the following ways:

The Java source program (. java file) is converted to a Java byte code (. class file) after it has been compiled by the Java compiler.

The ClassLoader is responsible for reading the Java byte code and converting it into an instance of the Java.lang.Class class. Each such instance is used to represent a Java class.

An object of the class can be created by using the Newinstance () method of this instance.

2, Class loader role:

The contents of the. class file become bytecode loaded into memory.

3, the structure of the class loader

The ClassLoader in Java can be broadly divided into two categories, one for the system, the other for Java application developers.

There are three main types of ClassLoader available in the system:

Boot class loader (BootStrap): It is used to load Java's core library, which is implemented with native code and does not inherit from Java.lang.ClassLoader.

Extension class loader (Extclassloader): It is used to load the Java extension library. The implementation of the Java virtual machine provides an extension library directory. The ClassLoader finds and loads the Java class in this directory.

System loader (Appclassloader): It loads Java classes according to the Classpath (CLASSPATH) of the Java application. In general, Java-applied classes are loaded by it.

It can be obtained by Classloader.getsystemclassloader ().





public class Classloadertest {public static void main (string[] args) {System.out.println (System.class.getClassLoader () );//nullsystem.out.println (ClassLoaderTest.class.getClassLoader (). GetClass (). GetName ());//appclassloader}}


4, delegate mechanism of class loader

Each classloader can only load a class at a specific location, and for a class that is not at its specified location, it can be delegated to other ClassLoader to load.

The specific is:

For example, a default Java application class should be loaded by Appclassloader,

First did not load, but entrusted to its father: Extclassloader, but ext also does not load, because it also has the father, again entrusted to Bootstap

Bootstap no father, find their own designated directory--rt.jar package under No, then let its son extclassloader to find, ext directory also did not, let it grandson Appclassloader to find.

Found, loading, can not find the report exception, will not look down (because from here)


5, custom class loader

1, step

①, inheriting abstract class ClassLoader

②, overwrite the Findclass (String name) method

③, returns the DefineClass () method. For example: Return defineclass (null, buf, 0, buf.length);



2. Encrypt class instances using a custom loader

A, the class to encrypt

Package Cn.jinfulin.day2.classloader;import Java.util.date;public Class Sercert extends Date {@Overridepublic String ToString () {return "I am an encrypted file";}}

b, encryption algorithm (only use simple 0,1 conversion, so that can do encryption algorithm, also can do decryption algorithm)

/* * Simple encryption algorithm */private static void Cypher (InputStream in,outputstream out) throws Exception {int b = -1;while ((b = in.read () )! =-1) {Out.write (b ^ 0xff);}}

C, start encrypting files

public static void Main (string[] args) {String Srcpath = "C:\\users\\ Jinfoling \\workspace\\staticimport\\bin\\cn\\jinfulin\\ Day2\\classloader\\sercert.class "; String destfilename = srcpath.substring (srcpath.lastindexof ("\ \") + 1); String destpath= "f:\\test\\" + destfilename; FileInputStream in = new FileInputStream (Srcpath); FileOutputStream out = new FileOutputStream (destpath); cypher (in,out);//system.out.println (new Sercert (). toString ()) ; Class clazz = new Classloadertest (). LoadClass ("Sercert.class"); Object obj = Clazz.newinstance (); System.out.println (obj);}

D, replace the class class in the bin directory with the encrypted class class, and then execute the error to prove the encryption is successful.


E, custom class loader for decrypting files (inherit ClassLoader, overwrite Findclass () method)

public class Classloadertest extends classloader{public static void main (string[] args) throws Exception {class Clazz = n EW classloadertest (). LoadClass ("Sercert.class"); Object obj = Clazz.newinstance (); System.out.println (obj);} /* Custom class loader for decrypting classes * @see Java.lang.classloader#findclass (java.lang.String) */@Overrideprotected class<?>          Findclass (string name) throws ClassNotFoundException {string classfilename = "f:\\test\\" + Name;inputstream ips=null;              try {ips=new fileinputstream (classfilename); Bytearrayoutputstream bos=new Bytearrayoutputstream ();//define Byte array stream cypher (Ips,bos);//Decrypt Ips.close ()              ;                        Byte[] Buf=bos.tobytearray ()//Remove the data in the byte array stream return DefineClass (null, buf,0,buf.length);//Load into memory          } catch (Exception e) {e.printstacktrace ();  } return null; }





Iv. final

Here JDK1.5 's new features are finally finished, and then we'll review the jdk1,5d new features are: Generics, enumerations, enhanced for loops, reflections, annotation classes, JavaBean, ClassLoader, static import, variable parameters, automatic unpacking.






New features of JDK1.5: JavaBean, annotation class, class loader

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.