Java Hardening Chapter (iv)---annotations, generics. Class loader. Threads

Source: Internet
Author: User

Three basic annotations for Java

@Deprecated: Marks this program element as obsolete, usually because it is dangerous or has a better choice.

@SuppressWarnings: Suppress the specified compiler warning.

@Override: Represents a method declaration that intends to override another method declaration in a superclass. If the method uses this annotation type for annotations but does not override the superclass method, the compiler generates an error message.

Meta Annotations @retention--define the existence area of the annotation class, there are three kinds of values: Retentionpolicy.source, Retentionpolicy.class, Retentionpolicy.runtime, corresponding to Java source files, class files, in-memory byte code.

Meta-annotations @target: Determining the available range of annotation classes, taking value Elementtype.method ...

Defining properties of a base type
Adds a string color () to the annotation class;
Reference: @MyAnnotation (color= "Red")

Once the annotation corresponding instance object is obtained by reflection, the corresponding method of the property is called through the object.
Myannotation a= (myannotation) AnnotationTest.class.getAnnotation (myannotation)
System.out.println (A.color);

Defines the default value for the property, string color (), default "red";

Value property String value ();
If an annotation has only one property named value, and you only want to set the property of value, you can omit it, @MyAnnotation ("Red");

Generic type

Terms that are involved in the Arraylist<e> class definition and the Arraylist<integer> class reference:
1. The entire arraylist<e> is called a generic type
2. E in arraylist<e> is called type variable or type parameter
3, the entire arraylist<integer> is called the parameterized type
4. An Integer in arraylist<integer> is called an instance of a type parameter or an actual type parameter
5, arraylist<integer> in the <> read typeof
6. ArrayList is called the original type

Parameterized type compatibility with original type-compile warning
collection<string> = new Vector ();
Collection = new Vector<string > ();

Parameterized types do not consider inheritance relationships for type parameters
Vector<string> v = new vector<object> (); Wrong!
Vector<object> v = new vector<string> ();//Wrong!

When you create an array instance, the elements of the array cannot use the parameterized type.

Defining generic Classes

Multiple methods in a class to use the same generic parameter, you define a generic at the class level.
public class genericdao<t>{
Private T field1;
public void Save<t obj>{}
Public T getById (int ID) {}
}

A generic at the class level is a parameterized variable based on the generic information specified by the reference class name.
Genericdao<string> Dao=null;
New Genericdao<string> ();

Attention
1. When you parameterize a generic type, it must be a reference type and cannot be a basic type.
2. When a class is declared as generic, it can only be called by instance variables and method calls (as well as inline classes), not by static variables and static methods. Because a class static member is shared by all parameterized classes, a static member should not have a class-level type parameter.

Get the parameterized type of generics by reflection

Vector<date> v = newvector<date> ();
The parameterized type of the generic is not available through V.getclass ().

Pass it to a method to implement this functionality.
public static void Applyvector (Vector<date> v) {}

Method applymethod =generictest.class.getmethod ("Applyvector", Vector.class);

type[] types = Applymethod.getgenericparametertypes ();

Parameterizedtype PType = (parameterizedtype) types[0];

System.out.println (Ptype.getrawtype ());//vector

System.out.println (ptype.getactualtypearguments () [0]);//date

Parent-child relationship and jurisdiction map between class loaders

When a Java virtual machine loads a class, which ClassLoader does it use?
◇ the class loader of the current thread is first loaded to load the first class in a thread
◇ If Class A refers to Class B, then the Java Virtual machine will use the class loader that loads class A to load Class B
◇ You can also call the Classloader.loaderclass () method directly to specify a class loader to load

Each class loader is loaded and then delegated to its ancestor's class loader.
When all ancestor class loaders are not loaded into the class, then go back to the initiator ClassLoader and still not load, then throw classnofoundexception, instead of looking for the initiator ClassLoader and the son, because there is no Getchild method. --loading from top to bottom.

Custom Class Loaders

Working mechanism
Parent class-->loadclass/findclass ()/Get the contents of the class file converted to bytecode->difineclass ()/Convert a byte array to an instance of class

Implementation steps
◇ The custom ClassLoader must inherit ClassLoader
◇ Cover Findclass method
◇ cover Difineclass () method

A review of the traditional threading mechanism

Two traditional ways to create threads

Writing run code in the Run method covered by the thread subclass

Involves a previous knowledge point: Can I throw a interruptedexception exception on the Run method declaration to omit the try...catch processing of the Thread.Sleep () statement inside the Run method?

Write code in the Run method of the Runnable object passed to the thread object

Summary: Looking at the source code of the thread class's run () method, you can see that both of these methods are called the Run method of the thread object, if the thread class's Run method is not overwritten, and a Runnable object is set for the thread object. The Run method invokes the Run method of the Runnable object.

Question: If you write a run code in the Run method covered by the thread subclass and pass a Runnable object for the thread subclass object, then the execution code of the runtime is the code for the subclass's Run method? Or the code for the Run method of the Runnable object?

A previous knowledge point involved: How to construct an anonymous inner class object how to call a non-default constructor method of a parent class.

Application of Timers

Timer class

TimerTask class

How multiple threads access shared objects and data

If each thread executes the same code, the same Runnable object can be used, and the Runnable object has that shared data, for example, the ticket system can do so.

If each thread executes different code, it is time to use a different runnable object, in the following two ways to implement the data sharing between these runnable objects:

Encapsulates the shared data in another object, and then passes the object one at a to each Runnable object. Each thread's method of manipulating the shared data is also assigned to that object to complete, which makes it easy to achieve mutual exclusion and communication for each operation that is performed on that data.

These runnable objects are used as internal classes in a class, shared data as member variables in this external class, and each thread assigns an action method to the shared data to an external class to enable mutual exclusion and communication of the various operations on the shared data. These methods for external classes are called by each Runnable object that is an inner class.

The combination of the above two ways: the shared data is encapsulated in another object, each thread to the method of sharing the data is also assigned to the object to complete, the object as a member of the external class variables or local variables in the method, The Runnable object for each thread acts as a member inner class or local inner class in an external class.

In short, it is best to synchronize mutually exclusive pieces of code in a few separate methods, these methods are placed in the same class, it is easier to implement the synchronization of mutual exclusion and communication between them.

The extreme and simple way to define a static variable in any class is to be shared by all threads.



Java Hardening Chapter (iv)---annotations, generics. Class loader. Threads

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.