Write high-quality code: 151 recommendations for improving Java programs--[98~105]

Source: Internet
Author: User

The recommended order of adoption is that the generic order in the list is T 、?、 Object

(1), List is a certain type of determination

List indicates that the elements in the list collection are of type T, and the specific type is determined at run time; list< > represents any type, similar to list, and list indicates that all elements in the list collection are of type object, because object is the parent class of all classes, so the list can also accommodate all class types, from this literal point of analysis, List is more customary: the coder knows that it is a certain type and is only determined at run time.

(2) List can read and write operations

The list can perform operations such as Add,remove, because its type is a fixed T-type and does not require any transformation operations during the encoding period.

The list is read-only and cannot be added or modified because the compiler does not know what type of element is contained in the list, and it cannot verify that the type is safe, and that the elements read by list<?> are of type object and need to be actively transformed. So it is often used for the return value of a generic method. Attention list<? > Although it is not possible to add, modify elements, but can delete elements, such as execute remove, clear, and so on, because its delete action is not related to the generic type.

The List can also read and write operations, but it needs to be transformed (up cast) when it performs a write operation, and needs to be shifted down while reading the data, and it has lost the meaning of generics.

Strict qualification of generic types with multiple bounds

The ToArray method of the list interface can convert a collection to an array, but the ToArray () method returns an object arrays, so it needs to change itself. When a generic class (especially a generic collection) is transformed into a generic array, the true type of the generic array cannot be a generic parent type (such as a top-level class object) and can only be a subtype of a generic type (including, of course, its own type), or a type conversion exception will occur. An array of type T is declared through the Reflection class array, because we cannot get the parameters of the generic type at run time, so we need the caller to actively pass in the T parameter type. List goto array:

 Public static <T> t[] ToArray (list<t> list,class<t> tclass) {//  Declares and initializes an array of type T t[] t = (t[]) array.newinstance (Tclass, List.size ());  for (int i = 0, n = list.size (); i < n; i++= list.get (i);} return t;}

Notice the particularity of class

The particularity of class:

No constructors: Classes in Java generally have constructors for creating instance objects, but the class class has no constructors and cannot be instantiated, and class objects are constructed automatically by the Java Virtual machine by invoking the Difineclass method in the ClassLoader when the class is loaded. You can describe the base type: Although the 8 basic types are not an object in the JVM, they generally exist in the stack memory, but the class class can still describe them, for example, you can use the Int.class to represent classes of type int. Its objects are singleton patterns: an Instance object of class describes a class and describes only one class, which in turn is true. A class has only one class instance object

Three ways to get a class object:

Class Property mode: such as the GetClass method of the String.class object, such as the New String (). GetClass () Forname method loading: Class.forName ("java.lang.String") Once the class object is obtained, it is possible to get annotations via Getannotations (), get the method through GetMethods (), get the constructor by GetConstructors (), etc.

Choose Getdeclaredxxx and getxxx in a timely manner

The GetXXX method obtains all public access levels, including methods inherited from the parent class, while getdeclaredxxx obtains methods of its own class, including the common (publicly) method, the private method, and is not restricted to access rights. What if you need to list all the methods that inherit from the parent class? Simple, get the parent class first, then use the Getdeclaredmethods, and then continue to recursion.

Set accessible to True when reflection accesses a property or method

The process of executing a method through reflection is as follows:

Gets a method object;
The isaccessible return value is then determined to be able to execute, and if the return value is false you need to call setaccessible (true);
Finally, invoke the Invoke execution method

Method method= ... ;         // Check if you can access        if (! method.isaccessible ()) {            method.setaccessible (true);        }         // Execution Method        Method.invoke (obj, args);

AccessibleObject Source:

 Public classAccessibleObjectImplementsannotatedelement {//define default Action permissions for reflection Suppressaccesschecks      Static Final PrivateJava.security.Permission access_permission =NewReflectpermission ("Suppressaccesschecks"); //whether to reset the security check, default to False      BooleanOverride; //constructor Function      protectedAccessibleObject () {}//can be obtained quickly, the default is not       Public Booleanisaccessible () {returnOverride; } }

AccessibleObject is the parent class of filed, Method, constructor, determines whether it can be accessed quickly without an access control check, and the value is saved in the AccessibleObject class with the override variable. However, the exact execution is determined in the Invoke method:

 Publicobject Invoke (Object obj, object ... args)throwsillegalaccessexception, IllegalArgumentException, invocationtargetexception {//whether it can be obtained quickly, whose value is the override variable of the parent class AccessibleObject        if(!override) {          //cannot get quickly, perform security checks            if(!reflection.quickcheckmemberaccess (Clazz, modifiers)) {Class<?> caller = Reflection.getcallerclass (1);            CheckAccess (caller, clazz, obj, modifiers); }} methodaccessor ma= Methodaccessor;//Read volatile        if(MA = =NULL) {Ma=acquiremethodaccessor (); }        //Direct Execution Method        returnma.invoke (obj, args); }

The accessible property is only used to determine if a security check is required, and if it is not required, it can significantly improve the performance of the system (of course, the security check is canceled, you can also run the private method, access the private property). After testing, in a large number of reflections, setting accessible to true can improve performance by about 20 times times. The Accessible property determines whether field and constructor are subject to access control checks. It is important to set accessible to true when setting field or executing constructor.

Dynamically loading class files using forname

Dynamic Loading is the loading of the required class library files while the program is running, and for Java programs, in general, a class file is loaded into memory at startup or initial initialization, while reflection can decide at run time whether a class needs to be loaded. Give me a chestnut:

 Public class Client103 {    publicstaticvoidthrows  classnotfoundexception {         // Dynamic Loading        Class.forName ("Com.study.advice103.Utils");}    } class utils{    // static code block static    {        System.out.println ( "Do Something ...");     }

Result: Do Something .....

Forname simply loads a class into memory, does not guarantee that an instance object will be generated, nor does it execute any method, and the static code is initialized, as determined by the class loading mechanism, not by the Forname method. That is, if there is no static property or static code block, Forname is the load class, and there is no execution behavior.

Dynamic loading is not suitable for arrays

An array is a very special class, although it is a class, but there is no class classpath defined.

String [] STRs =  new string[10];        Class.forName ("java.lang.string[]");

Will produce a bug:

Exception in thread "main" java.lang.classnotfoundexception:java/lang/string[] at    JAVA.LANG.CLASS.FORNAME0 ( Native Method)

To load an array dynamically:

   // creating arrays Dynamically        String[] STRs = (string[]) array.newinstance (String.  Class, 8);         // Create a multidimensional array        int [] ints = (int[]]) array.newinstance (int.  Class, 2, 3);

Write high-quality code: 151 recommendations for improving Java programs--[98~105]

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.