简体   繁体   中英

Java generic method that returns an instance of the passed params

I want to create a method that has a signature like the following:

public Dao<ClassA,ClassB> createDao(ClassA param1, ClassB param2)

but this isn't valid Java. I want to create a method that receives any class creates an Dao object then returns the new object

public Dao<ClassA,ClassB> createDao(ClassA param1, ClassB param2) {
    //Do some stuff that creates an object of Dao<param1,param2>
    return Dao<param1,param2>;
 }

Any ideas on how to pull this off?

Thank you.

Try this:

public <A,B> Dao<A,B> createDao(A param1, B param2) {
    return ...
}

Manh answer is correct. If you're dealing with Class objects, then

public <T, K> Dao<T, K> createDao(final Class<T> t, final Class<K> k) {
    return new Dao<>();
}

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