Dark Horse programmer--java High-tech-reflection mechanism

Source: Internet
Author: User
Tags connection pooling naming convention

Click Open Link Click Open Link click Open link android training, <a "> Click Open Link click Open link Java training, look forward to communicating with you! > Click the Open link to open the link

Reflection of the Cornerstone--class class

Each Java class in a Java program belongs to the same class, and the Java class name that describes such things is class.

Class does not have a constructor and cannot be a new object. How to get the class class instance, there are 3 methods:

The ① class name. Class class C1=date.class;

② object. GetClass Gets the byte code instance to which the object belongs: Person p=new person; Class C2=p.getclass (), then C2=person.class.

③ static method: Class.forName ("full class name"), the parameter must be the full class name, the package name. Class name.

Method of Class:

Boolean/isprimitive (): whether to represent an instance object of a base type

Boolean/isarray (): Is an instance object of an array type

Boolean/isinterface (): Is an instance object of the interface type

Reflection is the Java class that maps the various components in the Java class. The class class that represents the Java class provides a series of methods, such as variables, methods, constructors, modifiers, packages, and so on, which are represented by instance objects of the corresponding class (such as filed, method, Contructor, package, and so on).

Each member of a class can be represented by an instance object of the corresponding reflection API class, and these instance objects are obtained by invoking the class's methods.

Constructor class: Represents a constructor method in a class.

Get all the construction methods in a category:

Constructor[] Cons=class.forname ("java.lang.String"). GetConstructors ();

Get a construction method

Constructor con = class.forname ("java.lang.String"). GetConstructor ("Stringbuffer.class");

Parameters

Creating an Instance Object

Usual way: String Str=new string (new StringBuffer ("abc"));

Reflection mode: String Str= (String) con.newinstance (new Stringbuuffer ("abc"));

Class also has the Newinstance () method, which is a method of constructing an empty parameter.

Example: String str= (String) class.forname ("java.lang.String"). Newinstance ().

Filed class: Represents a member variable in a class

To get a member variable for a class:

Field/getfield (String name): Returns the specified public field.

Field[]/GetFields (): Returns all possible access to public fields for a class or object.

file/getdeclaredfiled (String name): Returns the specified field, including the private

Filed[]/getdeclaredfileds (): Returns all fields.

Field Method:

Object/get (Object obj): Returns the value of the field represented by this filed on the specified object.

Void/setaccessible (Boolean flag): Violent reflexes

Class<?>/GetType (): Gets the claim type of the field represented by this object.

Void/set (object Obj,object value): Sets the field that is represented by this field object on the specified object variable to the specified new value.

Exercise: Change the string contents of a member variable of all string types in an object to B.

Method class: Represents one of the member methods in a class

Get a method in the class class of a member method in one of the classes:

Method/getmethod (String name,class<?>...parametertypes); Gets the method of the specified public member. Parametertypes represents the byte code of the parameter type to get the method method.

Method[]/GetMethods (): Returns all public methods of this class.

Methods in the method class:

Object Invoke (Object Obj,object...args): This class of methods that run the Obj object. If the first argument passed is null, it means that the method corresponds to one of the static methods.

The difference between the Invoke method JDK1.4 and the JDK1.5 version:

JDK1.5 public Object Invoke (object Obj,object...args)

JDK1.4 public Object Invoke (object obj,object[] args)

In accordance with the JDK1.4 syntax, to pass an array's most arguments to the Invoke method, each element of the array corresponds to one of the arguments in the called method, so the code that calls the Charat method can also be rewritten with JDK1.4 to Charat ("str", the new Object The form of []{}].

Exercise: Perform the main method in a class in a reflective manner.

Import Java.lang.reflect.*;class Methoddemo {public static void main (string[] args) throws exception{// Gets the main method of the ClassDemo1 class. Method Me=classdemo1.class.getmethod ("main", string[].class);//Run the Main method Me.invoke (null, (Object) New string[]{}); Pass an array of type string to the Invoke method,//must be strong to the object, or the string array is then encapsulated into an object array, which is JDK1.5 new feature, passed//an array parameter to invoke, it will be automatically split, The elements inside the array are treated as arguments. }}


The difference between the Invoke method JDK1.4 and the JDK1.5 version:

JDK1.5 public Object Invoke (object Obj,object...args)

JDK1.4 public Object Invoke (object obj,object[] args)

In accordance with the JDK1.4 syntax, to pass an array's most arguments to the Invoke method, each element of the array corresponds to one of the arguments in the called method, so the code that calls the Charat method can also be rewritten with JDK1.4 to Charat ("str", the new Object The form of []{}].

Methods in class: Class<? Super T>/Getsuperclass (): Returns the class of the superclass.

String/getname (): Returns the name of the entity represented by this class object.

Reflection of arrays: arrays with the same dimension data type are of the same type and have the same class instance object.

The Getsuperclass () method that represents the class instance object of an array returns the parent class that corresponds to the class of object.

A one-dimensional array of basic types can be used as an object type, not as a object[] type, or as a one-dimensional array of non-primitive types, either as an object type or as a object[] type.

Array class: Provides a way to dynamically create and access Java arrays

Method Summary:

Static Object/get (Object Array,int Index): Returns the value of the index component in the specified Array object

Static Boolean/getboolean (Object Obj,int Index): Returns a value in a Boolean form.

Similar to this: GetChar () GetByte () getdouble () getfloat () getInt () Getlong () Getshort ()

Static int/getlength (Object array): Returns the length of the array object.

Static object/newinstance (class<?> componenttype,int length): Creates a new array with the specified component type and length.

Static void/newinstance (class<?> componenttype,int ... Dimensions): Creates a new array with the specified component type and dimension.

Static Void/set (Object array,int index,object value): Set new value

Static Void/setboolean (Object Array,int index,boolean Z): Sets the value of the index component in the specified array object to the specified Boolean value.

Similar to this are: SetByte () SetChar () setdouble () setfloat () Setint () Setlong () Setshort ()

Import java.util.*;import java.lang.reflect.*;import java.<span style= "color: #000000;" >io</span>.*;class Reflectdemo {public static void main (string[] args) throws exception{//create stream object InputStream is= New FileInputStream ("Prop.txt");//Create Properties Object Properties P=new properties ();//properties is associated with Flow p.load (is);// Use reflection to get the class Clazz=class.forname (P.getproperty ("ClassName") set in the configuration file;        Collection<person> h= (collection<person>) clazz.newinstance (); H.add (New Person ("Lisi", 15));        H.add (New person ("lisi02", 15));                 H.add (New person ("Lisi", 15)); System.out.println (H.size ());}} Class person{private String name;private int age;    Person (String Name,int age) {this.name=name; This.age=age;} Public String GetName () {return name;} public int getage () {return age;} public int hashcode () {return name.hashcode () +age*34;} public boolean equals (Object obj) {if (!) ( obj instanceof person) return false; Person p= (person) obj;if (This.name.equals (P.getname ())) return Age==p.getage (); returN Name.equals (P.getname ());}}  


Q: Is there a memory leak in Java

Answer: there is. Java in the object is the use of New or reflected methods created, these objects are created in the heap ( Heap ), the collection of all objects is Java the virtual machine is done through a garbage collection mechanism. determine if a memory space conforms to the garbage collection standard of two: one is to give the object a null value null, the following has not been called, and the other is to give the object a new value, so that the memory space is reallocated. In the underlying data structure is a collection of hash tables, if an object is stored, and then changes the object with the hash value of the property, the object will reallocate memory space, and then the reference address value of the collection will not be changed, the memory space will not be recycled, and the collection cannot delete the object, etc. Because the address value has changed, it causes a memory leak. Additional causes of memory leaks may include:

1. References to internal classes and external classes are prone to memory leaks

2, the use of listeners,java is often used to the listener, while releasing the object without the corresponding deletion of the listener may also lead to memory leaks.

3, the use of a large number of temporary variables, the object is not set to null in a timely manner may also lead to memory leakage

4, the connection of the database is not closed, including the connection pooling method to connect the database, if not shut down ResultSet , and so also can be a memory leak problem.

Example of a memory leak:

Vector v = new vector (10);

for (int i = 1; i<100; i++) {

Object o = new Object ();

V.add (o);

o = null;

}

Do not assume that the o object is recycled, actually v refers to these objects, and the referenced object GC is no way to recycle, which is likely to lead to memory leaks.

Introspection

Introspective introspector, primarily used to manipulate the JavaBean class. JavaBean is a special Java class that is used primarily to pass data information. The methods in this Java class are primarily used to access private fields, and the method names conform to some naming convention.

If you pass multiple information between two modules, you can encapsulate this information in JavaBean, which is often referred to as a value object (Value objects, or VO), which is stored in a private field in the class, and if you read or set the values of those fields, It needs to be accessed through a number of appropriate methods, such as having the property name in Class A, setting the Getname,setname to get its value, or setting a new value. The Name property is accessed through Getname/setname, which is the default rule. Classes that conform to such rules can be manipulated as Java beans.

The rules-compliant classes are the benefits of JavaBean operations:

Here you will find a class PropertyDescriptor:

1. In Java EE development, often used to javabean, many environments require to operate in javabean manner.

Some APIs for JavaBean operations are available in 2.JDK, and this set of APIs becomes introspective, and it is easier to manipulate JavaBean with an introspective API than a normal class.

The class in introspection:

PropertyDescriptor: Describes a property exported by a Java bean through a pair of memory methods.

Constructor: PropertyDescriptor (String propertyname,class<?> beanclass)

PropertyDescriptor (String propertyname,class<?> beanclass,string readmethodname,string writeMethodName)

PropertyDescriptor (String propertyname,method readmethod,method Writemethod)

Important methods:

Method | Getreadmethod (): Gets the method used to read the property value.

Method | Getwritemethod (): Gets the method used to write the property value.

void | Setreadmethod (Method Readmethod): Sets the methods that should be used to read property values.

void | Setwritemethod (Method Writemethod): Sets the method that should be used to write property values.

String | GetName (): Gets the programmatic name of this attribute.

Example: Test Javabeandemo.java

Import Java.lang.reflect.*;class Javabeandemo {public static void main (string[] args) throws exception{  // Create a Class A a1=new a () that conforms to the JavaBean rule;        /* The property name followed by the Setter,getter method, regardless of its variable name, is name, and if the second letter is lowercase, the first letter is also lowercase, and the property name and A1 byte-code object are passed to propertydescriptor.*/ PropertyDescriptor pd=new PropertyDescriptor ("X", A1.getclass ());// The methods Getreadmethod and Setwritemethod in the PropertyDescriptor class can be used to obtain A1 getter and setter methods. Method Readmethod=pd.getreadmethod (); Method Writemethod=pd.getwritemethod ();        Use the Invoke method of the method class in reflection to invoke the getter and setter methods. Writemethod.invoke (a1,9); System.out.println (Readmethod.invoke (A1));}} Class A, rules that conform to JavaBean class a{private int x;public void setName (int x) {this.x=x;} public int GetName () {return x;}
}

Introspector class: No constructor, cannot create object, the method inside is static

Important methods:

Static BeanInfo | Getbeaninfo (class<?> Beanclass): Introspection on JavaBean to understand all of its properties, exposed methods, and events.

BeanInfo Interface:

Propertydescriptor[] |getpropertydescriptors (): Returns an PropertyDescriptor array of editable properties supported by this bean.

Example: Indirect acquisition of a JavaBean class PropertyDescriptor tesrt Intrdemo.java via Introspector and BeanInfo interfaces

Import Java.beans.*;import java.lang.reflect.*;class Intrdemo {public static void main (string[] args) throws exception{A A1=new A (); All properties, public methods, and events of the class are indirectly obtained through Introspector and BeanInfo. BeanInfo Bi=introspector.getbeaninfo (A.class); Propertydescriptor[] Pds=bi.getpropertydescriptors (); Because you get a group, you have to traverse it to determine which one is the desired method for (PropertyDescriptor Pd:pds) {if (Pd.getname (). Equals ("name")) {method readmethod= Pd.getreadmethod (); Method Writemethod=pd.getwritemethod (); Writemethod.invoke (a1,9); System.out.println (Readmethod.invoke (A1)); }}}}//a class, conforming to JavaBean's rule class a{private int x;public void setName (int x) {this.x=x;} public int GetName () {return x;}}


The Beanutils Toolkit is primarily a convenient way for programmers to easily manipulate bean classes.

All the methods inside are static, without creating objects.

Important methods:

SetProperty (object, property name, value string)

GetProperty (object, property name) gets a string

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Dark Horse programmer--java High-tech-reflection mechanism

Related Article

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.