Summary of Java Exceptions and reflections

Source: Internet
Author: User
Tags first string

1. Exceptions

Exceptions, in short, are events that occur during a program's execution. It occurs during the run of the program, interfering with the normal instruction flow. If the exception is not handled, the program stops running after an exception occurs. Exceptions are divided into run and non-running exceptions. A non-running exception is also called a compilation exception. For compiler exception compiler requirements must be processed. Otherwise, it cannot run. The runtime exception compiler does not require forced processing. Run-time exceptions are generally caused by program logic errors, and the program should avoid such exceptions from a logical point of view as much as possible. They all inherit from the exception class. Running exceptions and non-running exceptions are also divided into categories of exceptions. The cause of an exception is a general problem caused by a procedural error or accidental external factors.

Inheritance relationship

If an exception is thrown inside a method, the exception is thrown into the calling method. If the exception is not handled in the calling method, it continues to be thrown to the caller of the method. This process will continue until the exception is handled. This process is called catching an exception.

2. Reflection

In the running state, all the properties and methods of this class are known to any class.

For any object, it can call any of its methods and properties;

This dynamic acquisition of information and the ability to dynamically invoke the object's methods is called the reflection mechanism of the Java language.

The mind map of reflection is as follows

When using reflection, you first need to get to the class class object, after you get this class, you can get all the contents of the class file.

The following is the specific reflection application method

1. Type conversion: A demonstration of turning map into person

The person class is a normal entity class that contains three private member properties and their set and get functions. Map is the map type frame used in the set frame, which can be added to generics. The specific conversion code is as follows

1 //param1: The type of data to convert Person.class string.class2  Public StaticObject Tobean (class<?> type,map<string,?extendsobject> map)throwsexception{3     4     //Introspector a tool class that specializes in processing beans. For example, to obtain a class attribute or method or construct5BeanInfo BeanInfo = Introspector.getbeaninfo (type);//parameters are passed the type of the class6     //call the Newinstance method to create this class7Object o =type.newinstance ();8     //method of obtaining O9Propertydescriptor[] PS =beaninfo.getpropertydescriptors ();Ten      for(inti = 0; i < ps.length; i++) { One  APropertyDescriptor p =Ps[i]; -         //gets the name of the method description (property name) if it is person--->name (name,age,sex) -String name =p.getname (); the         //is name the key in the map? -         if(Map.containskey (name)) { -             //get the value of a map by key -Object value =map.get (name); +             //by reflection, value is assigned to O -             //P.getwritemethod ();//Set Method +             //P.getreadmethod ();//Get Method A P.getwritemethod (). Invoke (O, value); at         } -     } -     //gets the value of the key in the map, and the value of -     returno; - } -  Public Static voidMain (string[] args)throwsException { inMap PMap =NewHashMap (); -Pmap.put ("name", "Zhang San"); toPmap.put ("Age", 1); +Pmap.put ("Sex", 2); -     //Map--->object thePerson p =NewPerson ("Zhang San"); *P.setage (1); $P.setsex (2);Panax NotoginsengPerson o = (person) tobean (person).class, PMAP); -System.out.println ("" +o.tostring ()); the}

The idea of the above code is to create a beaninfo relative to the desired class, and then through this BeanInfo object to get all the property names (corresponding to the map is all key-value pairs of keys), and then determine whether the map has the same name as the key to get the key, If there is one, get the value of that key through the map, then get the set method of the desired object through the PropertyDescriptor object, assign the value to the corresponding property, and finally return the object of the corresponding type.

Five ways to create new objects in 2.Java

1> calls the constructor of the class directly with new

New Person ("Zhang San");

2> creates an object using the Newinstance method in class, calling the constructor

1  Public Static voidTest1 ()throwsclassnotfoundexception, instantiationexception, illegalaccessexception{2         //1. Get the Class object3Class C = class.forname ("com. Person ");4         //2. Create a person object by using the Newinstance method in class5Person p =(person) c.newinstance ();6         //3. Check7P.setname ("Zhang San");8 System.out.println (P.getname ());9}

3> using the Newinstance method in constructors in class type

 public  static  void  test2 () throws   Nosuchmethodexception, SecurityException, Instantiationexception, Illegalaccessexception, IllegalArgumentException, invocationtargetexception{    1, gets the person type  Constructor c = person. class         .getconstructor ();  //  2, create method  person p = //  3, detect  p.setname ("Zhang San" 

4> is created by using the Clone method. The premise is that the Clone () method needs to be overridden in the entity class

/*** Entity class **/ Public classPersonImplementscloneable{PrivateString name; Private intAge ; Private intsex; @OverrideprotectedPerson Clone ()throwsclonenotsupportedexception { person person=NULL; person= (person)Super. Clone (); returnPerson ; }}/*** Clone function function in function class **/ Public Static voidtest3 () {//you need to override the Clone method to override the Cloneable interface. Very special .//implementing the Cloneable interface in the person classperson P1 =NewPerson ("Harry"); //call the Clone method to create a new object P2person P2 =NULL; Try{P2=P1.clone (); } Catch(clonenotsupportedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } System.out.println (P1==p2); }

The method of 5> serialization and deserialization, by which the object can be converted to a sequence of bytes, and the object is transferred to another machine.

3. Get method and action properties by reflection

1> the method of getting through reflection

The way to get a method by reflection is to declare a class object and then create a method object through the object's Getdeclaredmethod method, which is achieved by invoking the methods object's Invoke method. The specific sample code is as follows

1  Public Static voidTest5 () {2         Try { 3Class C = class.forname ("Com.hpe.ref.Person");4             //Get method person SetName getName5             //param1: String type of method name6             //param2: Parameter types for methods7Method m = C.getdeclaredmethod ("SetName", String.class);8             //Creating Object Objects9Object obj =c.newinstance ();Ten             //invoke Invoke method (method of Reflection call) One             //param1: Reflected class, value of Param2:m method AM.invoke (obj, "Zhang San"); -             //Validation -Method GM =c.getdeclaredmethod ("GetName"); the System.out.println (Gm.invoke (obj)); -}Catch(Exception e) { -             //TODO auto-generated Catch block - e.printstacktrace (); +         } -}

2> Getting properties by reflection

The way to get a property by reflection is to get the class object form of the object through class, and then get the property in the class as a string from field, and then manipulate the property through the Field object. The specific code is as follows.

 Public Static voidtest4 () {//create this person object at run time through reflection        Try{Class C= Class.forName ("Com.hpe.ref.Person"); Field field= C.getdeclaredfield ("name"); //gets the properties in the class as a string. field[] fs =C.getdeclaredfields (); //sets the property, if it is private, to have access to theField.setaccessible (true); Object o=c.newinstance (); //how the Set method----manipulate propertiesField.set (O, "Zhang San");        System.out.println (Field.get (o)); } Catch(ClassNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(nosuchfieldexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(SecurityException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(instantiationexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(illegalaccessexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }
3. Small bet: Analyze the following code features

The functional analysis of this piece of code

public int indexOf (int ch)

Returns the index within the string for the first occurrence of the specified character. The index (in Unicode code unit) is returned if the character that is associated with the value ch in this representation of the character sequence occurs for the object that occurs in the first string event.

Public stringbuffer Insert (int offset, char c)

Inserts a string representation of a char parameter in this sequence.

The overall effect is as if the second argument is converted to a string by method string.valueof (char) , and the character in the string is then inserted to the specified offset of this character sequence.

The offset parameter must be greater than or equal to 0, less than or equal to the length of the sequence.

So its function is, to the decimal point, each forward number of three bits, just insert a comma in the STR string. To achieve the number of digits effect.

Summary of Java Exceptions and reflections

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.