One: Annotations
1. Annotations (Annotation)
Annotations are quite a class or interface, and each annotation is an instance object
Usage form of annotations: @interface that is, @ annotation class name
Define the Annotation class:
@interface A
{...}
Classes that use the annotation class:
@A
Class b{}
To reflect on a class that uses the annotation class:
Class C {
B.class.isannotationpresent (A.class);
A a= (a) b.class.getannotation (A.class); }
2. The life cycle of the annotation class
The source file (. java), the bytecode file (. Class), the bytecode in memory (the runtime is loaded into memory).
Available enumeration classes: constant representation under Retentionpolicy
Retetionpolicy.source, Retetionpolicy.class, Retetionpolicy.runtime
3[email protected]
Java.lang.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.
For example, if the overridden method name is not the parent class in which to override the method name, the system will recognize and error.
ToString is written in ToString.
public class Person
{
@Override
public string toString ()
{
return null;
}
}
4[email protected]
Programmers are discouraged from using such elements, usually because it is dangerous or there is a better choice. The compiler warns you when you are using an disapproved program element or if you are performing an override in an disapproved code.
@Deprecated//@Deprecated indicates that the method is obsolete
public static void Sayhi ()
{
System.out.println ("Hi,world");
}
5[email protected]
Used to ignore some kind of warning, use @suppresswarnings (value=
{type,field,method,parameter,constructor,local_variable})
Eg: @SuppressWarnings (value={"deprecation"});//Ignore warnings of type "deprecation"
@SuppressWarnings (value={"deprecation"})
public class Demo
{
public static void Main (String []args)
{
A a=new a ();
A.ma ();
Class A
{
@Deprecated
public void Ma ()
{
System.out.println ("Ma method");
}
}
}}
6. Archive
A JDK provides an archive tool that can merge/compress multiple files or directories into a single file (. jar).
JAR–CVF Mytest.jar a.class B.class;//Package The two class files into a Mytest.jar file
Packaging commands for package xxx Xx.java file packaging
JAVAC-D package The path of the file after packaging the Java file
Javac-d. Person.java;//person.java file under "Package hq.packag;"
7[email protected]
Used to represent the life cycle of other annotations.
@Retention (Retentionpolicy.source)
Public @interface Annotationinter {
}
8[email protected]
Used to denote the scope of use of other annotations, and the different constants under enumeration ElementType specify the scope
Type (class, interface (including annotation type), enumeration), Field (field), Method (methods),
Annotation_type (annotation type), CONSTRUCTOR (construction method), package (packages), etc.
@Target ({Elementtype.type,elementtype.method})
Public @interface Annotationinter {
}
Two: generic type
Generics are provided to the Javac compiler to qualify input types in the collection, let the compiler block illegal input in the source program, and the compiler compiles a collection of type descriptions to remove the "type" information,
The efficiency of the program is not affected, and the return value of the GetClass () method is exactly the same as the original type for parameterized generic types. Because the generated bytecode of the compilation removes the generic type information,
As long as you can skip the compiler, you can add other types of data to a generic collection, for example, by using reflection to get the collection, and then calling its Add method.
Summary: Generics are only valid at the time of the compiler, are not valid at run time, and the "type" information that it indicates during runtime is removed as:
1. Generics (reference type only) using rules
The following terms are involved in the ArrayList class definition and the ArrayList class reference: The whole is called the ArrayList generic type
E in ArrayList is called a type variable or type parameter the entire ArrayList is called a parameterized type
An integer in ArrayList is called an instance of a type parameter or an actual type parameter
ArrayList in the <> read typeof
ArrayList called primitive types
The compatibility of the parameterized type with the original type:
Parameterized types can reference an object of the original type, compile a report warning,
For example, collection<string> C = new Vector ();//Can
The original type can reference an object of a parameterized type, compile a report warning, for example,
Collection C = new Vecto<string>r ();//Yes.
The third case:
Vector v1=new vector<string> ();//conforms to the top case
Vector<object> V=v1; can also, in accordance with the second case of the above
Parameterized types do not consider inheritance relationships for type parameters:
Vector<string> v = new vector<object> ();//Error
Vector<object> v=new vector<string> ();//Error
2. What is the generic type? Wildcard characters
Problem: Define a method that prints out all the data in a collection of arbitrarily parameterized types, how is this method defined?
Error mode:
public static void Printcollection (collectioncols) { for(Object obj:cols) {System.out.println (obj);}
The right way:
public static void Printcollection (collection<?> cols) { for(Object obj:cols) {System.out.println ( OBJ); } //cols.add ("string");//error, because it does not know its future match is bound to be string cols.size ();//Yes, this method has no relation to the type parameter cols = new hashset<date> (); }
Summary: Wildcard characters can be used to refer to various other parameterized types,? The variable defined by the wildcard is used primarily as a reference, and can be called a method that is not related to parameterization.
You cannot invoke a method that is related to a parameterized type.
3. What is the generic type? Expansion of wildcard characters
To qualify the upper bounds of a wildcard:
Correct: vector<? Extends number> x = new vector<integer> ();
Error: VECTOR<? Extends number> x = new vector<string> ();
To limit the bottom bounds of a wildcard:
Correct: vector<? Super integer> x = new vector<number> ();
Error: VECTOR<? Super integer> x = new vector<byte> ();
<?> and <E>
Class<?> c=new class<e> ();//correct
Class<e> c=new class<?> ();//error, ie? Can "=" any parameter, but a specific parameterized type "="? Error.
Summary: Qualifying wildcards always include yourself. can only be used as a reference and cannot be used to assign values to other variables
vector<? Extends number> y = new vector<integer> ();
vector<number> x = y;
The above code error, principle with vector<object > x11 = new vector<string> (); similar,
You can only assign a value by forcing the type conversion mode.
4. Methods for defining generics
- A generic type (or generic) in Java is similar to a template in C + +. But this similarity is limited to the surface, and generics in the Java language are basically implemented in the compiler.
- Used by the compiler to perform type checking and type inference, and then generate generic non-generic bytecode, an implementation technique known as erase (erasure)
- Java's generic methods are not as powerful as C + + template functions, and the following code in Java cannot be compiled: <T> t Add (t x,t y) {return (T) (x+y);
- return null; The angle brackets for the type parameter that is used to place the generic should appear after all other modifiers of the method and before the return type of the method, that is,
- Immediately before the return value. By convention, type parameters are usually represented in a single uppercase letter.
- In addition to using the extends qualifier when you apply generics, you can also use the extends qualifier when defining generics, such as the definition of the Class.getannotation () method.
- And you can use & to specify multiple boundaries, such as <v extends Serializable & cloneable> void Method () {}
- Only reference types can be the actual parameters of a generic method, swap (new int[3],3,5), and statements report compilation errors.
- Generics can be used in common methods, construction methods, and static methods.
- You can also use a type variable to represent an exception, called a parameterized exception, that can be used in the throws list of methods, but not in a catch clause.
You can have more than one type parameter in a generic, with a comma in the angle brackets in which they are defined,
For example: public static <K,V> V GetValue (K key) {return map.get (key);}
<T> must declare that this is for you to use "T" parsing, <t extends u&v> can also, <t Super u> can not public <T> T Method1 (T x,t y) { return y; } Public <t extends number> void method2 (t x) { } //Multiple parameters of T public static <K,V> V GetValue (K key) { V map = null; Return ( V) ((arraylist<integer>) map). get ((int) key);}//exception How to take the generic private static <t extends exception> void SayHello () throws T {try{}catch(Exception e) {throw (T) e;}}
5. Defining classes for Generics
public class genericdao<e> { //Multiple methods use the class E, put it above the class declaration <E> public void Add (e e) { } The //static method used by E, must be declared on its own method of <e>, cannot use the <E> public static<e> void method (e E) declared above the class { } public void Update (e e) { }}
Note: When you parameterize a generic type, the instance of the type parameter must be a reference type and cannot be a base type. When a variable is declared as generic,
Can only be called by instance variables, methods, and inner classes, not by static variables and static methods. Because a static member is a class that is parameterized by all
Shared, so static members should not have class-level type parameters
6.Type (interface)
Type is the public advanced interface for all types in the Java programming language. They include primitive types, parameterized types, array types, type variables, and base types.
Java.lang.reflect Interface Type
-
All known sub-interfaces:
-
Genericarraytype, Parameterizedtype, Typevariable<d>, Wildcardtype
-
All known implementation classes:
-
Class
7. Reflection, advanced application of generics
public class Generictest {public static void Main (string[] args) throws Exception { // How to get a specific generic type declared on a method //such as: public void Applyvector (Vector<date> v); How to know that the Vector is Date, that is, how to get the generic type in <T> //Resolution: Get the generic type on the method using the Getgenericparametertypes () in the Reflected methods class Method applymethod=generictest.class.getmethod ("Applyvector", Vector.class,set.class); Type [] tp= applymethod.getgenericparametertypes (); System.out.println (tp[0]); Parameterizedtype p= (Parameterizedtype) tp[1]; System.out.println (p.getactualtypearguments () [0]), public void Applyvector (vector<date> v,set< Hashset> s) {}}
Three: Class loader
1. Class Loader
- The ClassLoader is used when the program is running to use a class, and the class loader loads the bytecode of that class into memory for execution.
- Java Virtual machines can install multiple classloader, the system defaults to three main class loaders, each class loader is responsible for loading classes in different locations
- Bootstrap,extclassloader,appclassloader.
- Some ClassLoader are also Java classes, so there must be a non-Java class loader to load other Java class ClassLoader, this is boostrap.
- All ClassLoader in a Java Virtual machine are organized in a tree structure with a parent-child relationship. Each instantiation of a class loader object must be specified for it
- A parent class loader object, or the system default class loader as the parent.
2.ClassLoader
Construction Method:
ClassLoader ()/////Use the getSystemClassLoader()
ClassLoader returned by the method to create a new class loader that will act as the parent ClassLoader.
ClassLoader (ClassLoader parent);//Specifies the Parents class loader, the parent class may eventually call Bootstrap as the last parent.
Member Methods:
ClassLoader getParent();//returns the parent class loader for the delegate.
Static ClassLoader Getsystemclassloader();//Return to the System class loader
Class<?> loadclass(String name);//Use the specified binary name to load the class.
Class<?> findclass(String name);//Use the specified binary name to find the class.
Class<?> defineclass(Byte [] b,int off, int len);//Read byte array into class instance
3. The relationship of three types of loaders and the scope of the load class
BootStrap (startup class loader):
Common Java classes, such as the collection class under System,util, and so on.
Extclassloader (Extension class loader):
Follow the parental delegation model, that is, two kinds of loading classes, one is the LoadClass method, the other is the Findclass method. It overrides the Findclass method
When the parent class's LoadClass method cannot find a class, and it cannot be found, the class is loaded using the Findclass method, and an exception error is reported.
We can export our custom classes to the folder of that ClassLoader by right-clicking the export class.
Appclassloader (Application class loader):
Does not follow the parental delegation model, which is a way of loading a class, the LoadClass method, which overrides the LoadClass method,
Extends ClassLoader { String host; int port; publicbyte[] B =return defineclass (name, b, 0bytes// load the class data from the Connection
...} }
Follow the meaning of the parental delegation Model: it guarantees that classes with the same fully qualified name are not loaded repeatedly into the JVM, that is, classes with no duplicate names are loaded.
Does not follow the meaning of the parental delegation Model: There may be a large number of classes of the same name that are loaded into the JVM by different custom ClassLoader , that is, classes with different functions of the same name are loaded.
4. The class loader's (parent) delegation mechanism
When the class loader loads the class, it delegates the parent loader to find the class and loads the class, and the parent class is then delegated to the parent class until the ancestor loads the class .
If the ancestor does not load into the class, it will let the next level be searched until the original delegate's loader (if the Findclass method is overridden, the method is used to load the class).
If you don't, you're going to report an anomaly. classnotfoundexception
- The class loader () of the current thread is first
getContextClassLoader()
loaded to load the first class in a thread.
- If Class A refers to a class B,java, the virtual machine uses the class loader that loads class A to load Class B.
- You can also call the Classloader.loadclass () method directly to specify a class loader to load a class.
"Nine" in Java high-tech