"JAVA programming ideas" study notes: Chapter 14 (type information)

Contents
Java programming ideas (a) 1 to 4 chapters: Overview of
Java programming ideas (b) Chapter 5: initialization and cleanup
Java programming ideas (c) Chapter 6: Access
Section (d) of the 7 Java programming ideas: Complex with class
Java programming ideas (e) Chapter 8: polymorphism
Java programming ideas (six) Chapter 9: Interface
Java programming ideas (seven) Chapter 10: internal class
chapter (h) of the 11 Java programming ideas: holding the object
thinking in Java (nine) Chapter 12: abnormal
thinking in Java (x) Chapter 13: string
chapter (XI) of 14 Java programming ideas: the type of information

Chapter 14 type of information

14.1 RTTI

RTTI: (Runtime Type Identification) to identify the type of the operating phase

In Java, all types of conversions are checked for correctness at run time. This is the RTTI means: at run-time, to identify the type of an object.

 

14.1.1 loss of specific types of information issues

Type of polymorphic conversion performance: RTTI is the most basic form of use, but the conversion is not complete (polymorphic ≠ RTTI).

For example: If an array of container actually holds all the elements as Object, and then automatically transition back to the results declared type of access time. And the array when filling (hold) objects specific type may be declared a sub-type of class, so the transition into the array will be up to the declared type of object is lost hold of specific types. While access will only return Object transformation declared type, not specific sub-class type, so this transition is not complete.

Polymorphism in the performance of a specific type of behavior, but that things "polymorphic mechanism", is determined by the specific object reference is pointing, not equivalent to identify the specific type at run time.

 

14.2 Class Object

14.2.1 RTTI works in Java

To be able to identify the specific type at run time, indicating that there must be something to save a specific type information at run time, this thing is Class object.

 

Class object: a special object. I.e. Class object represents a runtime type information, which includes information related to the class.

a. In fact Class object is used to all the "normal" class of objects that are created.

B. Each class has a Class object. In other words, every time writing and compiled a new class, it will generate a Class object (more properly, that is stored in .class file of the same name).

c. Class object **. java files compiled into ** is generated when the class file and save it in the .class file.

 

14.2.2 Class object to generate the object (Object conventional, non-Class object)

JVM is running programs using a so-called "class loader" subsystem (class loader subsystem) to generate a class object by loading Class object (or .class files).

 

All classes are at the first time you use it, dynamically loaded into the JVM. When the program first use static member of the class, the class will be loaded, indicating that the constructor is a static method, even in front of the constructor did not add the static keyword.

 

Thus, Java programs are not being fully loaded before it starts to run, it is only when each part must be loaded. (C ++ static loading this language is very difficult to do.)

 

 

14.2.3 type of work (process) loader

step1: a first check Class object class (.class files or understanding) has been loaded;

step3: Once the Class object (.class file) is loaded (loaded into memory), it is used to create all objects of this class.

among them:

First execution when loaded a. Static class clause.

b. Class objects are loaded only when needed,

c. static initialization performed when the class is loaded.

 

 

Method (two kinds) 14.2.4 obtain a Class object reference

方法1:Class.forName()

Class.forName (net.mrliuli.rtti.Gum) is a static member of the class Class that returns a Class object reference (Class object and other objects, we can get and manipulate a reference to it (which is the class loader worker's)). When using this method, if net.mrliuli.rtti.Gum has not been loaded on to load it. In the loading process, Gum's static clause is executed.

In short, whenever you want to use at run-time type information, you must first obtain a Class object to the right of reference.

By Class.forName (), it is a convenient way, this way is not necessary to obtain the Class object reference holds objects of that type. (Ie not by creating or no objects of this type when you can get Class object reference.)

 

Method 2: created objects Object.getClass ()

If you already have a type of the object, you can get its Class object by calling the object getClass () method references. This method belongs Object, return the actual type of the object represented by the object reference Class.

 

Method 3: class literal .class, such FancyToy.class. This is the recommended method.

 

14.2.5 Class useful methods included

getName () Get the fully qualified name of the class

getSimpleName () Get the name of the package does not contain the name of the class

getCanonicalName () Gets the fully qualified class name

isInterface () to determine whether an object is a Class Interface

The getInterfaces () returns an array of Class object implements the interface

getSuperclass () Returns the object's direct base classes Class

Wherein: newInstance () This method relies on the representative class Class object must have a default constructor (Nullary constructor, i.e. no argument constructor) accessible by, or otherwise InstantiationException IllegalAccessException exception is thrown.

 

Note: Class references do not have any further information at compile type, so it just returns an Object reference, but this is an Object reference point to a specific type represented by this Class references. The need to transition to a specific type of Object to send messages outside of it.

 

14.2.6 class literals

14.2.6.1 Use class literal .class Class is another method of obtaining an object reference.

As FancyToy.class. This is the recommended method.

It will be subject to inspection (and therefore do not need to put the try block) at compile time, so simple and safe. Eradicated call to forName (), so it is more efficient.

Class literal .class applicable not only to ordinary class, also applies to the interface, and an array of basic types.

Note that when you use a reference to create .class Class object will not automatically initialize the Class object.

 

14.2.6.2 In order to use the class to do the preparatory work actually involves three steps:

step1: loaded. This is performed by a class loader. This step finds the byte code (generally designated in the CLASSPATH find the path), and creates a Class object from these bytecodes.

step2: link. The class byte code verification, allocates storage for a static field, and, if necessary, it will resolve references to all other classes at the link stage this class is created.

step3: initialization. If the class has a superclass, then initializing it, and performing a static initial static initializer block.

14.2.6.3 Initialization inert

Initialization is delayed to a static method (constructors implicitly static) executed when the number of static or very first reference domain, i.e. effectively achieved initialized as "inert."

Remarks:

Very few static field: static final int staticFinal2 = ClassInitialization.rand.nextInt (1000); not compile-time constants, reference to it will be initialized to force the class.

Constant static field: static final int staticFinal = 47;

class Initable{

static final int staticFinal = 47; // constant static field

static final int staticFinal2 = ClassInitialization.rand.nextInt (1000); // non-constant static field (not compile-time constants)

}

class Initable2{

static int staticNonFinal = 147; // non-constant static field

}

 

public class ClassInitialization {

public static Random rand = new Random(47);

public static void main(String[] args) throws Exception {

Class initalbe = Initable.class; // .class acquired using a class literal Class object reference is not initialized

System.out.println (Initable.staticFinal); // constant static field for the first time reference is not initialized

System.out.println (Initable.staticFinal2); // non-constant static field for the first time reference, initializes

System.out.println (Initable2.staticNonFinal); // non-constant static field for the first time reference, initializes

Class initable3 = Class.forName ( "net.mrliuli.rtti.Initable3"); // use Class.forName () Gets the Class object references, initializes

}

}

 

 

14.2.7 Generalization of Class references

14.2.7.1 Class object type limit <T>

Class Class object to a reference point is always, at this time, the Class object may be of various types, when using generic syntax type Class Class object reference points to be defined, which makes Class object type variable too specific, so that the compiler will do some extra work compile-time type checking. Such as

public class GenericClassReferences {

public static void main(String[] args){

Class<Integer> genericIntClass = int.class;

genericIntClass = Integer.class; // Same thing

}

}

 

14.2.7.2 using wildcards? Relax restrictions on the Class object type

Wildcard <?>: Is part of the Java generics, said that "anything"?.

<?> Class intClass = int.class; and Class intClass = int.class; are equivalent, but better than using Class Class, because it shows that you are clear to use a non-specific class reference, <?> before choosing a non-specific version, not because of your negligence.

 

Limited wildcard: <? extends **> or <? super **>

Class<? extends Number>

Class<? super Number>

The extends keyword in combination with a wildcard as Class <? Extends Number>, a range is created, so that this reference is defined as a Class Number type or subtype.

 

 

Do first before checking 14.2.7.5 Type Conversion

RTTI forms including:

Embodiment 1: Conversion of conventional type, such as (the Shape), is the object's Class object type

Mode 2: Keyword instanceof. It returns a Boolean value that tells us that the object is not a particular type or subclass. As if (x instanceof Dog) statement will check if the object x belongs to the Dog class.

Embodiment 3: Dynamic instanceof: Class.isInstance () method provides a way to dynamically test object. Class.isInstance () method so that we no longer need instanceof expressions.

 

14.2.7.6 isAssignableFrom()

Class.isAssignableFrom (): the call type may be assigned parameter type, i.e., determines whether the parameters passed in the call type inheritance structure (or call type is a call-type subclass).

 

14.3 registered factory

Factory Method (Design Patterns): The object is to create a working class yourself.

public interface Factory<T>{

T create();

}

 

Equivalence Class of 14.4 instanceof and

instanceof and isInstance () to keep the concept of type, it means "you are the kind you, or you are the class derived from it?"

== and equals () does not consider inherited - it is either this exact type or not.

 

14.5 reflection:

Run-time type information (Reflection: runtime class information)

Class and class libraries with the concept of reflection java.lang.reflect were supported.

RMI: Remote Method Invocation (Remote Method Invocation): the ability to create and run objects on remote platforms across the network.

 

The real difference is that RTTI and reflection:

For RTTI, the .class file is opened and checked at compile time. (In other words, we all call the object's method can use the "normal" way.)

For the reflection is, .class file is unavailable at compile time, so be open and check .class file at run time.

 

14.6 Dynamic Proxy

Java's dynamic proxy agents thought more than a step forward, because it can dynamically create proxy and dynamically handle calls to the proxy approach.

In the dynamic proxy all calls made will be redirected to a single call processor, its job is to reveal the type of call and determine appropriate countermeasures.

You can create a dynamic proxy by calling the static method Proxy.newProxyInstance (), it requires three parameters:

ClassLoader loader a class loader, which typically may be obtained from a class loader object has been loaded in

Class <?> [] Interfaces want the agent to a list of interfaces to be implemented (not a class or an abstract class)

InvocationHandler h a processor interface to achieve call

Dynamic agent can redirect all calls to the call processor, it is often passed a "real" object (i.e., object proxy) a reference to the calling processor such that the processor in performing its call mediation task may be forwards the request (that is, to call the actual object).

14.6.1 advantage of dynamic proxies and fly in the ointment

Advantages: dynamic and static proxy proxy comparison, the biggest advantage is that all the methods declared in the interface method calls are transferred to a central processor (InvocationHandler.invoke) in the process. In this way, the more the number of interface methods, we can be flexible, without the need for a static transfer agent like every method that.

The only drawback: it has never been able to get rid of the shackles of only supports interface agent, because its design is destined to regret this.

 

14.7. Null object

eg:

 

14.7.2 pile simulation objects (Mock Objects & Stubs)

Logical variation empty object and the object is to simulate the pile.

 

14.8. Interface with the type of information

By using reflection, and can reach all method calls a class, the method including the private! If you know the name of the method, you can call setAccessible (true) on its Method object, and then access the private methods.

class A {

private void g(){

System.out.println("B.g()");

}

}

 

/**

* Reflected by calling all methods (including private)

*/

public class HiddenImplementation {

static void callHiddenMethod(Object obj, String methodName, Object[] args) throws Exception{

Method method = obj.getClass().getDeclaredMethod(methodName);

method.setAccessible(true);

method.invoke(obj, args);

}

public static void main(String[] args) throws Exception{

callHiddenMethod(new A(), "g", null);

}

}

 

14.9 summary

Polymorphic:

RTTI:instanceOf/ isInstance()

reflection:

Dynamic Agent:

 

Published 216 original articles · won praise 67 · views 950 000 +

Guess you like

Origin blog.csdn.net/cbk861110/article/details/104096499