简体   繁体   中英

Creating a Java Interface with methods that accept any class as a parameter

I am creating an application in JSF and using hibernate. For every JSF page I want to perform CRUD operations. To Simplify my coding, I want to create an interface that has the four methods to perform CRUD. I want the methods in the interface to accept any class as a parameter.

Here is my sample code:

interface performCrud
{
    public void Create(Class cl);
    public void delete(Class cl);
    public void update(Class cl);
    public void read(Class cl);
}

class newuser implements performCrud
{

    @override
    public void Create(UserDao userdao)
    {

    }

    //Other implementations Follows

}

class newproduct implements performCrud
{

   @override
   public void Create(productDao productdao)
   {

   }

   // Other implementations Follows

}

If I understand what you mean, you should use generics :

interface performCrud<T>
{
    public void Create(T cl);
    public void delete(T cl);
    public void update(T cl);
    public T read();
}

class newuser implements performCrud<UserDao>{

    @override
    public void Create(UserDao userdao)
    {

    }
    ....
}

Oh, and BTW, your read method should probably return T instead of accepting an argument of type T . I changed the interface accordingly.

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