Java step-by-step Tour (ii)--recognize class, reflection concept, Constructor,fiald,method, reflection Main method, array reflection and practice

Source: Internet
Author: User

Java step-by-step Tour (ii)--recognize class, reflection concept, Constructor,fiald,method, reflection Main method, array reflection and practice

We continue to talk about Java, this time more interesting, that is reflected

I. Understanding Class

To reflect, you have to understand a class--class, and we know that each Java class in a Java program belongs to the same thing, and we usually use classliability to describe it, The concept of reflection from the JDK1.2 out, history is relatively long, this class is not a keyword Oh, this is a class, he represents a kind of things;

    • We get the bytecode object in the final analysis.

Here we have three ways to get the corresponding instance object (class type)

    • 1. Class name.
    • 2. Object. GetClass
    • 3.class.forname ("class name");-common

We're going to write a little program to go over it.

publicclass CalssTest {    publicstaticvoidmain(String[] args) throws ClassNotFoundException {        "liu";        Class class1 = str1.getClass();        Class class2 = String.class;        Class class3 = Class.forName("java.lang.String");        System.out.println(class1 == class2);        System.out.println(class1 == class3);        System.out.println(class2 == class3);    }}

By printing the results we can know that we are all output the same byte code, so the result is true, we see, our class actually has a method

System.out.println(class1.isPrimitive());System.out.println(Integer.class == int.class);System.out.println(int.class == Integer.TYPE);

The result of printing is true,false,true, then what does this three mean? This is left to everyone to guess, it should be easy to know.

    • Whether the isprimitive is an underlying type or primitive type

So what kind of arrays are we?

Purpose, as long as the type that appears in the source program, have their own class type, include Int[],void etc.

Two. The concept of reflection

Good. Knowing the magic of class, we can take a look at the mechanism of reflection.

The concept of Reflection: reflection is to map the various components of the Java class into the corresponding Java class, for example, a Java class with a class class object to represent, a class of components, member variables, methods, construction methods, packages and other information, also used by a Java class to represent, Just like the car is a class, the engine in the car, the gearbox is also a class, indicating that Java class classes to provide a series of methods to get the variables, methods, construction methods, modifiers, packages and other information, which is used for the corresponding class instance object representation, the palace is Field,method, Contructor,package, etc.

Each member of a class can be represented by an instance object of the corresponding reflection API class, invoking a class to invoke a variety of methods, and then we'll talk about

Three. Constructor

Represents a method of constructing a class, and we use code to see

publicclass CalssTest {    publicstaticvoidmain(String[] args)throws NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {        //得到String的StringBuffer构造方法        Constructor<String> constructor = String.class.getConstructor(StringBuffer.class);        String str = constructor.newInstance(new StringBuffer("str"));        System.out.println(str);    }}

By using the method obtained to use the same type of example above, and then look at newinstance, we can get the construction method of setting parameters, we look at the reflection of member variable

Four. Fiald

Here we simulate a class that acts as a reflection object

publicclass FialdClass {    publicint x;    publicint y;    publicFialdClass(int x,int y) {        this.x = x;        this.y = y;    }}

So our actual operation is:

 Public classcalsstest { Public Static void Main(string[] args) {Try{//Assign value to X, y firstFialdclass Fclass =NewFialdclass (Ten, -);//Reflection member variableField field1 = Fclass.getclass (). GetField ("x"); Field field2 = Fclass.getclass (). GetField ("Y");//Specify ObjectSystem. out. println (field1.Get(Fclass)); System. out. println (Field2.Get(Fclass)); }Catch(Nosuchfieldexception E1) {//TODO auto-generated catch blockE1.printstacktrace (); }Catch(SecurityException E1) {//TODO auto-generated catch blockE1.printstacktrace (); }Catch(IllegalArgumentException e) {//TODO auto-generated catch blockE.printstacktrace (); }Catch(Illegalaccessexception e) {//TODO auto-generated catch blockE.printstacktrace (); }    }}

So that we can reflect directly to the value of the member variable, here we do a little exercise to test the reflection of our member variables.

Exercises
    • Suppose we have an object that has a number of string type member variables, and our requirement is to change all the corresponding string contents "B" to "a"

The topic has our thinking, the first thing to do is to define an object

 Public classFialdclass { Public intX Public intY PublicString str1 ="Boy."; PublicString str2 ="BBQ"; PublicString STR3 ="Hello"; Public Fialdclass(intXintY) { This. x = x; This. y = y; } @Override PublicStringtoString() {return "Fialdclass [x="+ x +", y="+ y +", str1="+ str1 +", str2="+ str2 +", str3="+ STR3 +"]"; }}

OK, here are three member variables of type string, so how do we go about reflection?

/** * Suppose we have an object with a number of string-type member variables, we need to change all the corresponding string contents "B" to "a" * @author LGL * */ Public  class calsstest {     Public Static void Main(string[] args)throwsexception{Fialdclass Fclass =NewFialdclass (5,Ten);//Get all the employee variablesfield[] fields = Fclass.getclass (). GetFields (); for(Field field:fields) {//filter String type            if(Field.gettype () = = String.class) {//valueString oldValue = (string) field.get (Fclass); String newvalue = Oldvalue.replace ("B","a");            Field.set (Fclass, newvalue);    }} System.out.println (Fclass); }}

Here the idea is still relatively clear, we step by step to filter, and finally changed the value

Five. Method

If the front is not commonly used, then this I believe you will definitely like, that is, methods, method, we have to see how to use it!

publicclass CalssTest {    publicstaticvoidmain(String[] args) throws Exception{        "abc";        //反射charAt方法        Method method = String.class.getMethod("charAt"int.class);        //作用对象 第几个        System.out2));    }}

Here I reflected the method of string Charat, take the second char, so print out is C

This actually applies to an expert mode, who calls this data, who is this expert, and now we think about it if our code is written like this:

System.out.println(method.invoke(null, 2));

Here we do not pass the object, but pass a null in, then we know this method is called what? In the overall analysis, only the static method of static modification does not need the object, which means that he calls the object;

In JDK1.4 and JDK1.5, the parameters of invoke are somewhat different, but we are now 1.8, naturally this we do not need to consider and pursue;

Six. Reflection Main method

Now let's think about how to do the Main method of a class by reflection, which is more fun, this is the equivalent of an exercise, and the topic is:

    • Write a program that can execute the main method of the class based on the class name provided by the user.

And we're going to think about it before we write this procedure, and we'll look at the Main method:

publicstaticvoidmain(String[] args) {    //main方法}

Have you found out that the argument to this main method is an array, and if we call this method by reflection, how do we pass arguments to the Invoke method?

In previous old programmers might be in the tangled JDK1.4 and JDK1.5 invoke differences, but we don't have to think about these, because our version is JDK1.8, so let's first write a class that needs to be called:

publicclass MainClass {    publicstaticvoidmain(String[] args) {        for (String arg : args) {            System.out.println("Main:" + arg);        }    }}

OK, this class is the value of the printed array, so how do we actually reflect the reflection? The traditional method of invocation is this:

MainClass.main(newString"Hello" });

It's not so simple when we reflect, we need this:

 Public classcalsstest { Public Static void Main(string[] args) throws Exception {//Mainclass.main (new string[] {"Hello"});        //Specify class name        //String className = args[0];        //Specify Main methodMethod main = Class.forName ("MainClass"). GetMethod ("Main", String[].class);//Call the Main methodMain.invoke (NULL, (Object)NewString[] {"Hello","LGL"}); }}

Why does it need to be strong to object? Not a good pass array? Because the JDK is in order to be compatible with the old version, if you pass an array with more than one value will be unpacking, I now declare an object is to tell him that I am just an object, to avoid object exceptions, we look at the output of the result:

It means that we have succeeded in the call, and that here it pulls the reflection of the array and the relationship of the object, and we continue to look at it;

Seven. Reflection of arrays

The array is actually an object, so we must be clear, right?

    • Array terms with the same dimension and element type have the same type, that is, have the same class instance object
    • The Getsuperclass () method that represents the class instance object of the array returns the parent class object as the class

Here we take an array as an example, let's verify the bytecode:

3 };4 };//trueSystem.out.println(arr1.getClass() == arr2.getClass());//[ISystem.out.println(arr1.getClass().getName());

The first one is true and the first one is verified, and the result of the second output is [I, what does this mean? [Represents an array, I represents an int type, which is an array of type int

Just take a look at the JDK reference document, please.

Next, let's take a look at how the array's reflection concrete practice looks like!

Eight. Array reflection Practice

We've got a good title, so it might seem a little more vivid.

    • Title: How do I get the elements in the array?

By looking at the API documentation, we know that this array can be reflected

So how does this array work?

Suppose I now encapsulate a printing method, this printing method is very simple, I define an object parameter, you pass in what, I will print what, if pass the array, I will print one by one, this understanding should be more clear, then we actually operate you how?

 Public classcalsstest { Public Static void Main(string[] args) throws Exception {int[] arr = {1,3,5,7,9,2,4,6,8,Ten};    PrintObject (arr); }Private Static void PrintObject(Object obj) {//Get byte codeclass<? Extends object> classs = Obj.getclass ();//Determine if it is an array        if(Classs.isarray ()) {//Get length            intLen = array.getlength (obj);//Remove each one             for(inti =0; i < Len; i++) {System. out. Print (Array.Get(obj, i)); }        }Else{System. out. println (obj); }    }}

But how do you want to ask me this array of data type, I did not get to, do not know why!!!

Good, relatively simple reflection of the basis of the sneak pass, interested friends can understand, but also into the group: 5,559,744,491 up to explore!

Java step-by-step Tour (ii)--recognize class, reflection concept, Constructor,fiald,method, reflection Main method, array reflection and practice

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.