4

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

1
  • 4
    Do you need to use generics here? (Sometimes you don't, and Object is good enough) Commented Feb 9, 2015 at 5:05

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.