Implement the return type in java
Hello,
I am about to write a class method and return an object of type that has passed the class argument. I know a method of the object EntityManager the fact:
Here is the code which I will be using
Code:
<T> Find T(<T> EntityClass Class, Object primaryKey)
But how to implement it? I can not find a code that does it. Any help will be appreciated. Thanks in advance.
Re: Implement the return type in java
Hello,
You might be a bit more explicit? Why do you return a type that you pass an argument? If it is, as I suppose, because the type passed as argument change (normal), why not create an interface or class? This will be easy to do and it will be helpful in future if you want to import the class and it's methods. I recommend you to do some study on the object oriented programming.
Re: Implement the return type in java
Hello,
I am interested in this topic and I have done some study on this but the method is to search for any object type. I must just give the class and object and it will send me the object correctly cast. It works if my return is Object, but it forced me to return the caster.
But finally I found. I tried everything, except the solution
Code:
Public <T> Find T(<T> Class class, Object pk)
Instead of T, we can put what you want except? It helps to have a return type configurable.
Re: Implement the return type in java
Hello,
This method is part of a class "service" that links with the EntityManager. You can try something like this.
Here is the code
Code:
Public <T> Find T(<T> Class class, Object primaryKey) {
return em.find(class, pk);
}
With this method, you might as well get a "moving target" that subject "bill", no cast.
Code:
Invoice inv = service.find(bill.class, pkFacture);
Movement mt = service.find(Stroke.class, pkMvmt);
Re: Implement the return type in java
Hello,
Yes of course! It is simply the use of Generics on a method and not to the scale of the class (the <T> is before the method definition). It is very convenient because it saves them the relationship between the parameters and the method returns. It is widely used in the classroom Collections among others. Hope this will help you and you will get going with your program.