Java exceptions and reflection

JAVA Exception Classification and Handling

concept

}

final Entry<K,V> getEntryUsingComparator(Object key)

{

K k = (K) key;

// Get the comparator of the TreeMap

Comparator<? super K> cpr = comparator;

if (cpr != null)

{

// start from the root node

Entry<K,V> p = root;

while (p != null)

{

// Compare the key with the key of the current node

int cmp = cpr.compare(k, p.key);

// If the key is less than the key of the current node , search to the " left subtree "

if (cmp < 0)

p = p.left;

// If the key is greater than the key of the current node , search to the " right subtree "

else if (cmp > 0)

p = p.right;

// Not greater than, not less than, that is, the target Entry has been found

else

return p;

}

}

return null;

} If a method cannot complete the task according to the normal way, you can exit the method through another path. In this case a

An object that encapsulates the error message. In this case, the method exits immediately without returning any value. Additionally, other calls to this method

The code cannot continue to execute, and the exception handling mechanism will hand over the code execution to the exception handler.

Anomaly classification

Throwable is the superclass of all errors or exceptions in the  Java language. The next layer is divided into  Error and  Exception

Error

1. The Error class refers to internal errors and resource exhaustion errors of the  java runtime system. Applications do not throw objects of this class. if appear

If such an error occurs, in addition to notifying the user, the rest is to try to make the program terminate safely.

ExceptionRuntimeExceptionCheckedException

2. Exception has two branches, one is runtime exception  RuntimeException , the other is  ckedException .

RuntimeException such as: NullPointerException, ClassCastException; one is a checked exception

CheckedException , such as  IOException and SQLException caused by  I/O errors .  RuntimeException are those that can

Superclass for exceptions that can be thrown during normal operation of  the Java virtual machine. If  a RuntimeException occurs , it must be the programmer's

wrong .

Checked exception  CheckedException : Generally, it is an external error. This kind of exception occurs at the compilation stage, andJavacompiler will force the program to

 To catch this kind of exception, you will be asked to try catch the program that may have an exception . This type of exception generally includes several methods

noodle:

1. Trying to read data at the end of the file

2. Attempting to open a malformed  URL

3. Try to find  the class object according to the given string , and the class represented by this string does not exist

Exception handling

There are three forms of throwing exceptions, one is throw  ,

A  throws , there is also a system that automatically throws an exception. Try catch capture exception targeted processing

The difference between Throw and  throws :

different location

1. Throws is used on a function, followed by an exception class, which can be followed by more than one; while  throw is used in a function, followed by an exception pair

elephant.

The functions are different:

2. Throws is used to declare an exception, so that the caller only knows the possible problems of this function, and can give a pre-processing method; throw

Throw a specific problem object, execute to throw , the function is over, jump to the caller, and throw the specific problem object

to the caller. That is to say, when  the throw statement exists independently, do not define other statements below, because they cannot be executed.

3. Throws means that there is a possibility of exceptions, and these exceptions may not necessarily occur; throw means that an exception is thrown, and the execution

throw must have thrown some kind of exception object.

4. Both are passive ways to handle exceptions, just throw or may throw exceptions, but the exceptions will not be handled by the function, the real

Handling exceptions is handled by the upper layer call of the function.

javareflection _

dynamic language

A dynamic language means that a program can change its structure during runtime: new functions can be introduced, existing functions can be deleted, etc.

structural changes. For example, the common  JavaScript is a dynamic language. In addition,  Ruby, Python , etc. are also dynamic languages, while  C ,

C++ is not a dynamic language. From the perspective of reflection,  JAVA is a semi-dynamic language.

The concept of reflection mechanism (know all the properties and methods of the class in the running state)

The reflection mechanism in  Java means that in the running state, for any class, all the properties and methods of this class can be known; and for

For any object, you can call any method of it; this function of dynamically obtaining information and dynamically calling object methods becomes

The reflection mechanism of the Java language.

Application of reflection

public static void main(String[] args) {

String s = "abc";

if(s.equals("abc")) {

throw new NumberFormatException();

} else {

System.out.println(s);

}

}

int div(int a,int b) throws Exception{ return a/b;} compile-time type and runtime type

Many objects in  a Java program have two types at runtime: compile-time type and runtime type. The compile-time type is declared by

The practical type of the object is determined, and the runtime type is determined by the type actually assigned to the object. like:

Person p=new Student(); Among them, the compile-time type is  Person , and the runtime type is  Student .

The compile-time type of has no access to the concrete method

The program may also receive an object passed in from the outside during runtime. The compile-time type of the object is  Object, but the program needs to call the object

method of the runtime type. To solve these problems, programs need to discover the real information of objects and classes at runtime. However, if the edit

It is impossible to predict which classes the object and class belong to at translation time, and the program can only rely on runtime information to discover the real information of the object and class.

When you have to use reflection.

Java Reflection  API

The reflection API is used to generate information about classes, interfaces or objects in the JVM .

1. Class class: the core class of reflection, which can obtain the attributes, methods and other information of the class.

2. Field class: The class in the Java.lang.reflec package, which represents the member variable of the class, which can be used to obtain and set the attribute value in the class.

3. Method class: The class in the  Java.lang.reflec package, which represents the method of the class, which can be used to obtain the method information in the class or execute

line method.

4. Constructor class: The class in the  Java.lang.reflec package, which represents the construction method of the class.

Reflection usage steps (get  Class object, call object method)

1. Get the  Class object of the class you want to operate . It is the core of reflection. Through the  Class object, we can call the method of the class arbitrarily.

2. Call the method in the  Class class, which is the use phase of reflection.

3. Use the reflection  API to manipulate the information.

 3 ways to get  Class object

Call the getClass() method of an object

Person p=new Person();

Class clazz=p.getClass();

Call the class attribute of a class to get the Class object corresponding to the class

Class clazz=Person.class;

Use the forName() static method in the Class class ( safest / best performance )

Class clazz=Class.forName(" full path of the class "); ( most commonly used )

After we have obtained the  Class object of the class we want to operate, we can obtain and view the methods and properties in the class through the methods in the  Class class.

sex. 

// Get the Class object of the Person class

Class clazz=Class.forName("reflection.Person");

// Get all method information of the Person class

Method[] method=clazz.getDeclaredMethods();

for(Method m:method){

System.out.println(m.toString());

}

// Get all member attribute information of the Person class

Field[] field=clazz.getDeclaredFields(); for(Field

f:field){

System.out.println(f.toString()); Two ways to create objects

newInstance() of the Class object

1. Use  the newInstance() method of  the Class object to create an instance of the corresponding class of the  Class object, but this method requires the

The class corresponding to the Class object has a default empty constructor.

Call newInstance() of the Constructor object

2. First use  the Class object to obtain the specified  Constructor object, and then call  the newInstance() method of the  Constructor object

To create an instance of the class corresponding to the  Class object , through this method you can select the construction method to create an instance.

JAVA annotations

concept

Annotation (annotation) is a way and method provided by  Java to associate information and metadata ( metadata ) of elements in metaprograms

Law. Annatation ( annotation ) is an interface, the program can obtain the  Annotation object of the element in the specified program through reflection , and then

Get the metadata information in the annotation through the  Annotation object.

4 standard meta annotations

The role of meta-annotations is to annotate other annotations.  Java 5.0 defines  four standard  meta-annotation types, which are used to provide

For explanation of other  annotation types.

Object range modified by @Target

@Target explains the range of objects modified by Annotation :  Annotation can be used for  packages , types (classes, interfaces, enumerations)

Enumeration, Annotation type), type members (methods, constructors, member variables, enumeration values), method parameters and local variables (such as

loop variable, catch parameter). The use of  target in the declaration of  the Annotation type can clarify the target of its modification

@Retention defines the length of time to be retained

Retention defines the length of time that the  Annotation is retained: it indicates at what level the annotation information needs to be saved, and is used to describe the annotation

The life cycle (that is: in what scope the described annotation is valid), the value ( RetentionPoicy ) is determined by:

n SOURCE: effective in the source file (that is, the source file is retained)

n CLASS: valid in the class file (that is, the  class  is reserved)

n RUNTIME: valid at runtime (that is, reserved at runtime)

}

// Get all the constructor information of the Person class

Constructor[] constructor=clazz.getDeclaredConstructors();

for(Constructor c:constructor){

System.out.println(c.toString());

}

// Get the Class object of the Person class

Class clazz=Class.forName("reflection.Person");

// Create an object using the .newInstane method

Person p=(Person) clazz.newInstance();

// Get the constructor and create the object

Constructor

c=clazz.getDeclaredConstructor(String.class,String.class,int.class);

// Create object and set properties

Person p1=(Person) c.newInstance(" Li Si ", " Male ", 20); @Documented description -javadoc

@Documented is used to describe that other types of  annotation should be used as the public  API of the annotated program member , so it can

Documented by tools such as  javadoc .

@Inherited states that a marked type is inherited

The @Inherited meta-annotation is a marker annotation, @Inherited states that a marked type is inherited. If one uses

If  the annotation type modified by @Inherited is used in a  class , the  annotation will be used in the subclass of the  class

kind.

annotation processor

Annotations would be no more useful than comments if there were no methods and workarounds for reading them. In the process of using annotations, it is very important

The essential part is created using annotation processors. Java SE5 extends the API of the reflection mechanism to help programmers quickly construct custom

definition annotation processor. An annotation processor is implemented below.

/1 : ** Definition Annotation */

@Target(ElementType.FIELD)

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface FruitProvider {

/** Supplier number */

public int id() default -1;

/** Supplier name */

public String name() default "" JAVA inner class

Not only variables and methods can be defined in Java classes, but also classes can be defined, so the classes defined inside the class are called inner classes. by definition

Inner classes are divided into four types: static inner classes, member inner classes, local inner classes, and anonymous inner classes.

static inner class

A static class defined inside a class is a static inner class.

1. The static inner class can access all the static variables and methods of the outer class, even if it is  private .

/** * Supplier Address */

public String address() default "";

}

//2 : Annotation use

public class Apple {

@FruitProvider(id = 1, name = " Shaanxi Red Fuji Group ", address = " Yan'an Road, Xi'an City, Shaanxi Province ")

private String appleProvider; public void setAppleProvider(String

appleProvider) { this.appleProvider = appleProvider;

}

public String getAppleProvider() { return appleProvider;

}

}

/3 : ********* Annotation Processor **********/

public class FruitInfoUtil { public static void getFruitInfo(Class<?> clazz)

{

String strFruitProvicer = " Provider information: ";

Field[] fields = clazz.getDeclaredFields();// Obtain processing annotations through reflection

for (Field field : fields) { if

(field.isAnnotationPresent(FruitProvider.class)) {

FruitProvider fruitProvider = (FruitProvider)

field.getAnnotation(FruitProvider.class);

// where the annotation information is processed

strFruitProvicer = " Provider ID: " + fruitProvider.id() + " Provider Name: "

+ fruitProvider.name() + " Supplier Address: "+

fruitProvider.address(); System.out.println(strFruitProvicer);

}

}

}

}

public class FruitRun { public static void main(String[] args) {

FruitInfoUtil.getFruitInfo(Apple.class);

/******** output result **********/

// Supplier Number: 1Supplier Name: Shaanxi Red Fuji Group Supplier Address: Yan, Xi'an, Shaanxi Province

}

}

public class Out {

private static int a;

private int b;

public static class Inner {

public void print() {

System.out.println(a);

}

} } 2. The static inner class is consistent with the general class, and can define static variables, methods, construction methods, etc.

3. Other classes need to use the " outer class . Static inner class " method to use the static inner class , as follows: Out.Inner inner = new

Out.Inner();inner.print();

4. There is a static inner class Entry inside the Java collection class HashMap . Entry is an abstraction of elements stored in HashMap .

HashMap internally maintains the  Entry array to store elements, but  Entry is transparent to users. like this with external classes

Those that are closely related and do not depend on external class instances can use static inner classes.

member inner class

A non-static class defined inside a class is a member inner class. Member inner classes cannot define static methods and variables ( except final modified

outside). This is because the internal class of the member is non-static, and the static member is initialized first when the class is initialized. If the internal class definition of the member is allowed

Static variables, then the initialization order of static variables of member inner classes is ambiguous.

public class Out {

private static int a;

private int b;

public class Inner {

public void print() {

System.out.println(a);

System.out.println(b);

}

}

}

Local inner classes (classes defined in methods)

A class defined in a method is a local class. If a class is only used in one method, consider using a partial class.

public class Out {

private static int a;

private int b;

public void test(final int c) {

final int d = 1;

class Inner {

public void print() {

System.out.println(c);

}

}

}

}

Anonymous inner class (to inherit a parent class or implement an interface, use new directly to generate a reference to an object)

For anonymous inner classes, we must inherit a parent class or implement an interface. Of course, we can only inherit a parent class or implement an interface.

mouth. At the same time, it does not have the class keyword, because the anonymous inner class directly uses new to generate a reference to an object.

public abstract class Bird {

private String name;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name; JAVA generic

Generics provide a compile-time type safety detection mechanism that allows programmers to detect illegal types at compile time. The essence of generics is to refer to

Numerical types, that is to say the type of data being manipulated are specified as a parameter. For example, we want to write a sorting method that can sort integer numbers

Groups, arrays of strings, or even any other type of array, we can use  Java generics.

generic method()

You can write a generic method that can receive parameters of different types when called. Depending on the parameter types passed to the generic method,

The compiler handles each method call appropriately.

1. <? extends T> indicates that the type represented by the wildcard is a subclass of the  T type.

2. <? super T> indicates that the type represented by the wildcard is the supertype of the  T type.

generic class

The declaration of a generic class is similar to the declaration of a non-generic class, except that a type parameter declaration part is added after the class name. Like generic methods, generic

The type parameter declaration part of a type class also contains one or more type parameters, separated by commas. A generic parameter, also known as a

A type variable is an identifier used to specify a generic type name. Because they accept one or more parameters, these classes are called parameter

Numerical classes or parameterized types.

}

public abstract int fly();

}

public class Test {

public void test(Bird bird){

System.out.println(bird.getName() + " able to fly " + bird.fly() + " meter ");

}

public static void main(String[] args) {

Test test = new Test();

test.test(new Bird() {

public int fly() {

return 10000;

}

public String getName() {

return " Big Goose ";

}

});

}

}

// generic method printArray

public static < E > void printArray( E[] inputArray )

{

for ( E element : inputArray ){

System.out.printf( "%s ", element );

}

} type wildcard ?

Type wildcards are generally used  ? instead of specific type parameters. For example,  List<?> is logically

The parent class of all  List< concrete type arguments > such as List, List, etc.

type erasure

Generics in Java are basically implemented at the compiler level. Types in generics are not included in the generated  Java byte code

informational. The type parameters added when using generics will be removed by the compiler when compiling. This process is called type erasure.

 Types such as List and  List defined in the code will become  List after compilation . All the JVM sees is  the List , and the ones appended by the generic

Type information is invisible to  the JVM .

The basic process of type erasure is also relatively simple. First, find the concrete class used to replace the type parameter. This concrete class is generally  Object .

If an upper bound on the type parameter is specified, that upper bound is used. Replace all type parameters in the code with concrete classes.

Guess you like

Origin blog.csdn.net/2301_76965813/article/details/130539757