Java static generic method __java

Source: Internet
Author: User
Tags comparable

Java introduced generics in JDK 5, which is a lot easier to use, and here's a very common generic usage:

list<string> list = new arraylist<string> ();
Generic methods use

Not only can it be used in collections, but it is often used when defining classes, interfaces, and methods, but there are still not many scenarios for generic methods to use. Here's a look at the implementation of the maximum number of two numbers. Simple use of generic classes and generic methods: generic classes (interfaces)

Package me.codeboy.test;

/**
 * Generic Test
 * Created by Yuedong on 9/12/16.
 *
/public class Mathtest<t extends comparable> {public

    static void Main (string[] args) {
        mathtest< integer> mathTest1 = new mathtest<integer> ();
        mathtest<double> mathTest2 = new mathtest<double> ();
        System.out.println (Mathtest1.max (1, 2));
        System.out.println (Mathtest2.max (2.0, 3.0));
    }

    Private T Max (t T1, T T2) {return
        T1.compareto (T2) > 0? t1:t2;
    }
}
generic Method
/**
 * Generic Test
 * Created by Yuedong on 9/12/16.
 *
/public class Mathtest {public

    static void Main (string[] args) {
        mathtest mathtest = new Mathtest ();
        System.out.println (Mathtest.max (1, 2));
        System.out.println (Mathtest.max (2.0, 3.0));
    }

    Private <t extends comparable> t max (t T1, T T2) {return
        T1.compareto (T2) > 0? t1:t2;
    }
}
static Generic method
/**
 * Generic Test
 * Created by Yuedong on 9/12/16.
 *
/public class Mathtest {public

    static void Main (string[] args) {
        System.out.println (max (1, 2));
        SYSTEM.OUT.PRINTLN (Max (2.0, 3.0));

    private static <t extends comparable> t max (t T1, T T2) {return
        T1.compareto (T2) > 0? t1:t2;
    }
}

advantages and disadvantages of generic methods

The advantages are obvious, the code is much simpler, or it can be said to be simpler than the generic generic generics, with a static generic approach to Android that frequently uses the Findviewbyid method, known as the most awesome Android code, but there are two sides to everything. Static generic methods also have a corresponding disadvantage, and look at a piece of code:

Import java.util.ArrayList;
Import java.util.List;

/**
 * Test Entry
 * Created by Yuedong on 9/10/16.
 *
/public class Test {public

    static void Main (string[] args) {
        list<string> List = new Arraylist<> ;();
        List.add ("test");

        General conversion
        arraylist<string> RESULT1 = (arraylist<string>) list;

        static generic conversion
        String RESULT2 = convert (list);

    private static <T> T convert (Object a) {return
        (t) A;
    }
}

The above code is compiled through, run an exception, why this phenomenon occurs. This is because the Java generic method is pseudo generic and will be erased at compile time. The generic method has clearly formulated the corresponding type in the class construction, but in the static generic method, the type cannot be inferred directly, lacks the explicit type, finally causes the type transformation exception.

Exception in thread "main" Java.lang.ClassCastException:java.util.ArrayList cannot is cast to java.lang.String
principle Exploration

The

sees the result above and wonders what the generic method eventually converts after the type erase, and the compiled class file for the reverse-compiled static generic method is as follows:

 Compiled from ' Test.java ' public class Test {public test (); code:0: Aload_0 1:invokespecial #1//Method Java/lang/object. "
    <init> ":() V 4:return public static void Main (java.lang.string[]);                  code:0: New #2//class java/util/arraylist 3:dup 4:invokespecial #3 Method Java/util/arraylist. " <init> ":() V 7:astore_1 8:aload_1 9:ldc #4//String Test 11 : Invokeinterface #5, 2//Interfacemethod Java/util/list.add: (ljava/lang/object;) Z 16:pop 17:al
      Oad_1 18:checkcast #2//class java/util/arraylist 21:astore_2 22:aload_1
      23:invokestatic #6//Method convert: (ljava/lang/object;) Ljava/lang/object; 26:checkcast #7//Class java/lang/string 29:astore_3 30:return} 

You can see that the CONVERT function will be converted to the corresponding byte code after the final conversion: (ljava/lang/object;) Ljava/lang/object; parameter is type object and returns the object type, and in the next Checkcast operation, the exception is thrown because of the different List and String types.

    private static <t extends list> T convert (Object a) {return
        (T) A;
    }

For the above code decompile corresponding method convert: (ljava/lang/object;) ljava/util/list; , you can see that the parameter is type object at this time and is returned to the list type. Summary

Although generics in Java are pseudo generics, generics can make code more concise, but require special attention to type conversions when using common generic methods and static generic methods.

More articles please visit Xiao Fat Xuan.

Related Article

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.