简体   繁体   中英

Java Generics - How to write static methods with type arguments?

Coming from a C++ background, I was hoping to write few util static methods which could be used throughout my application without necessarily going via object creation. And I was hoping to use the equivalence of function templates in Java Generics. At this point, I want to clarify that I am learning Java generics.

But on trying that, I could see that the compiler would not allow me to do so. And I could see some very good discussion as well here . But then I played around with the warning message a little bit to write an inner static class with similar touch, and as per my intuition it worked there. Now obviously, it is clumsy to access inner classes which I have presented below. I wonder why this has been designed this way in Java and good will this inner class offer with generics to outside classes.

public class ReflectionBasics<X, Y> {

    public static void findMax (X xData, Y yData ){
       // compiler error - cannot reference static type to non-static type X 
    }

    public void findMin(X xData, Y yData){
        // this is fine
    }

    static final class InnerClass<E> {
        public void findMin(E data){
            // this will work
        }
    }
}

Clumsy Accessor:

class AccessorClass{
    AccessorClass(){
        ReflectionBasics.InnerClass<Integer> myData = new ReflectionBasics.InnerClass<Integer>();
        myData.findMin(400);

    }
}

If you want to put type parameters on a method, you just stick them before the return type (which you probably didn't want to be void ):

public static <T extends Comparable<T>> T findMax(T a, T b) {
    ...
}

In most cases, you can skip the type parameters at the call site, and they'll be inferred for you:

Integer max = WhateverClass.findMax(integerA, integerB);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM