I have a Java method which has to accept generic object.
Public void myMethod(Object<T> anyClassObject) {
//handle code
}
The method should accept object of any class and I have to manage the content of the object. I am not an expert in Generics. So please help me to achieve this using Generics.
my need is to create a method which any class's instance. And then I have to save the object in database.
For saving into database, have to specify the persistent entity class as usual.
For example,
mongoTemplate.createCollection(One.class)
For an other entity,
mongoTemplate.createCollection(Two.class)
like the above.
I have to write a method which can be accessed in common
To accept a reference to any object, you don't even need generics. Simply use Object
as the type:
public void myMethod(Object someObject) {
// code ...
}
Generics become necessary only when you want to have multiple things with related types. For example, here's a method that takes a reference of any type, and returns the same reference with the same type:
public <T> T doNothing(T someObject) {
return someObject;
}
doNothing("").length()
will compile - if doNothing
is passed a String
, then it returns a String
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With