Java Programming Ideas chapter_14 type information

Source: Internet
Author: User

This chapter does not revolve around a noun:type recognition of RTTI (run-time type identification) run-time

It is understood that the author is the introduction of the concept from C + +, anyway, it doesn't matter, understand and can concatenate this chapter knowledge is the most important

The content of this chapter is actually for the type information service, the main content has

A. Class object

Problem:

What is the process of creating a 1.Class object?

What are the different ways to create a 2.Class object?

3. Using generics

Before you know the type information, you need to know the class object

To create a class object, you need to find the. class file for this class, and the found class file is loaded into memory as a bytecode, so all objects of this class can be created from the in-memory class object

There are three ways to create objects in this chapter

The first: by means of the new constructor

The second type: Class CLS = Class.forName ("Fully qualified name"); Cls.newinstance ();

The Third class CLS = class:. class; Cls.newinstance ();

Say 3 more farfetched, the second and third through the virtual constructor newinstance () to create the object, Newinstance () 2 points need to note: ① interface cannot Newinstance;② class must have empty constructors

What's the difference between the three ways, where other points of knowledge are involved

1. Call a static method of a class, have you created an object

The answer is no, because there are no more than 3 ways to create objects, just loading the. class file into memory, initializing the class, and not creating the object

 Public classTest { Public Static voidMain (string[] args) {//TODO auto-generated Method StubA.print (); }}classa{Static{System.out.println ("Static Block"); }         PublicA () {System.out.println ("Construction Method"); }         Public Static voidprint () {System.out.println ("Print class A"); }}

The results are printed as follows:

Static block
Print Class A

2. There is no difference between class.forname ("fully qualified name") and. Class

There are differences, Class.forName will take the initiative to load static method blocks, while. class does not initialize after the first reference to a static method or a very few static domain.

 Public Static void Main (string[] args) {        //  TODO auto-generated method stub        try  {            Class.forName ("chapter_14.a");         Catch (ClassNotFoundException e) {            //  TODO auto-generated catch block             E.printstacktrace ();        }    }

Printing: Static block

 Public Static void Main (string[] args) {        //  TODO auto-generated Method stub        class CLS = A.class ;}

Not printed

A little digression, why we normally see the static constants that are accessed are usually like this

public static final int CONSTANT = 5;

Instead of

public static int CONSTANT = 5;

The reason is that static final is a compile-time constant, class. CONSTANT does not require initialization of the class to be read

The meaning of introducing generics is simply to provide a compile-time check, and the 15th chapter will focus on generics, which provides several concepts here

Unlike Ordinary. class, generic newinstance () returns the exact type of the object

class a{} class extends a{}class<A> ClsA = A.Class= Clsa.newinstance ();

What about Super class?

Super B> ClsA = B.class= Clsa.newinstance ();

The superclass gets not the exact type, but just the object

What about the inheritance class?

extends A> clsb = B.class= Clsb.newinstance ();

At this point is the type of the parent class, in the next learning, we will often use this way to create objects, this is a polymorphic, it belongs to the type information

Two. Check before type conversion

Problem:

1. The meaning of the check before type conversion and the way to check

Avoid classcastexception by an explicit downward transition

There are 3 kinds of common inspection methods, instanceof, Isinstance, IsAssignableFrom

As an example:

class Implements iface{} class extends a{} Interface iface{}

The first kind of instanceof

//class to check the type of the class instantiation object itselfclass<?SuperB> ClsA = B.class. Getsuperclass (); Object Obja=clsa.newinstance (); System.out.println (ObjainstanceofA);//true//class to check the type of the subclass instantiation objectClass clsb = B.class; Object OBJB=clsb.newinstance (); System.out.println (OBJBinstanceofA);//true//interface Check types that implement class instantiation objectsSystem.out.println (ObjainstanceofIface);//trueSystem.out.println (OBJBinstanceofIface);//true

The second type: isinstance

class<?SuperB> ClsA = B.class. Getsuperclass (); Object Obja=clsa.newinstance (); Class CLSB= B.class; Object OBJB=clsb.newinstance ();//class object that examines the instantiated object of the class itselfSystem.out.println (Clsa.isinstance (Obja));//trueSystem.out.println (Clsb.isinstance (OBJB));//true//class object to check the instantiation object of the subclassSystem.out.println (Clsa.isinstance (OBJB));//true//the class object of the interface examines the instantiated object of the implementation classClass clsiface = Iface.class; System.out.println (Clsiface.isinstance (Obja));//trueSystem.out.println (Clsiface.isinstance (OBJB));//true

The Third kind of isassignablefrom

class<?SuperB> ClsA = B.class. Getsuperclass (); Object Obja=clsa.newinstance (); Class CLSB= B.class; Object OBJB=clsb.newinstance ();//class object that examines the class objectSystem.out.println (Clsa.isassignablefrom (ClsA));//true//class object that examines the class object of the subclassSystem.out.println (Clsa.isassignablefrom (CLSB));//true//the class object of the interface examines the class object that implements theClass clsiface = Iface.class; System.out.println (Clsiface.isassignablefrom (ClsA));//trueSystem.out.println (Clsiface.isassignablefrom (CLSB));//true

The above 3 ways to summarize, is the following picture

Type checking on the other hand also illustrates the relationship between classes and classes, and the relationship between classes and interfaces.

Three. Registered Factory

Problem:

1. What is the use of registering a factory?

Registering a factory is the combination of factory method design patterns and additions, in this chapter, or with type information, adding objects to the base class that implement classes, but all based on the factory design pattern, the benefit of "avoiding new data additions to the structure". The examples in this chapter are very graphic and very good, and if I have good examples, I will definitely put the link

Four. Empty objects

Problem:

1. What is an empty object

2. Meaning of using empty objects

Typically, an empty object is a singleton with an attribute that cannot be modified

Suppose that a variable of a class is an empty object by default, then if you want to change the property of the variable, you need to recreate an object to replace the empty object, I am talking nonsense, but this is the essence of the empty object, combined with the following code, think about

Interfacenull{}classperson{Private FinalString first; Private FinalString last; Private FinalString address;  PublicPerson (string first, string last, address of string) {Super();  This. First =First ;  This. Last =Last ;  This. Address =address; } @Override PublicString toString () {return"Person [first=" + First + ", last=" + Last + ", address=" + address + "]"; }        Static classNullpersonextendsPersonImplementsnull{PrivateNullperson () {Super("None", "none", "none"); } @Override PublicString toString () {return"Nullperson"; }        }         Public Static FinalPerson NULL =NewNullperson ();}

This code is copied from the Java programming idea of the empty object section, there is also a knowledge point: Not every class will have a default empty constructor, like the person class above is actually no empty constructor, the problem is that the constructor parameters with the final decoration, you can go to explore the next.

Five. Reflection

1. What is the reflection mechanism?

2. How to use the reflection mechanism in a dynamic proxy way

Reflection is a program that opens and checks. class files at run time, so reflection is dynamic, and the concept of reflection is supported in the JDK using class and Java.lang.reflect classes libraries

The use of reflection is due to the properties of some classes, methods do not have access to the package, and we have to access to do something

It is conceivable that package access does not work for reflection, including private adornments, proprietary inner classes, and anonymous internal methods

Examples of applications to reflection are the eventbus of component communication in Android, which can be downloaded to see the source code

Reflection can also be used for dynamic proxies (say more, dynamic proxy nature or type information) The main code is copied from the book

 Public classTest { Public Static voidMain (string[] args) {A Obja=NewA (); Iface Iface= (Iface) proxy.newproxyinstance (Iface.class. getClassLoader (),NewClass[]{iface.class},NewDynamicproxyhandler (Obja));    DoSomething (Iface); }         Public Static voiddosomething (Iface Iface) {iface.dosomething (); }}classAImplementsiface{@Override Public voiddosomething () {System.out.println ("A dosomething"); }}Interfaceiface{ Public voiddosomething (); }//all calls will be redirected to this single processor .classDynamicproxyhandlerImplementsinvocationhandler{PrivateObject proxied;  PublicDynamicproxyhandler (Object proxy) {proxied=proxy; } @Override PublicObject Invoke (Object proxy, Method method, object[] args)throwsThrowable {//TODO auto-generated Method Stub        returnMethod.invoke (proxied, args); }}

Here are 3 points to note: 1.. Redirect a single processor, what is the calling object; 2. the iface created must be an interface object , and the second parameter to be passed to create an interface object is the class array, which contains the interface names for all proxied. class; 3. Relationship between dynamic proxy and type information

Summary: Type information is essentially about transitioning up or down

Java Programming Ideas chapter_14 type information

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.