简体   繁体   中英

How can I restrict a method accepting certain user defined class objects using generics?

I have 2 empty classes emp and reset . I have method in another class which will accept only these two classes these I need to achieve using generics . Both these classes are not related to each other in any manner.

package abstracta;

import generics.emp;
import generics.nonemp;
import generics.reset;

// A Simple Java program to show working of user defined
// Generic functions

class Test
{
    // A Generic method example
    static <T> void genericDisplay ( T element)
    {
        System.out.println(element.getClass().getName() +
                           " = " + element);
    }

    // Driver method
    public static void main(String[] args)
    {
         // Calling generic method with Integer argument
        genericDisplay(new emp());

        // Calling generic method with String argument
        genericDisplay(new reset());

        genericDisplay(new nonemp());// should not accept  . restrict this class
    }
}

i want genericDisplay not to accept nonemp class

You haven't shown us your code, but the common solution to this is to create a common interface.

Both classes then implement this interface and the Generic just applies to the the interface as the type of its input parameter.

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