0

I have a Java method which has to accept generic object.

public <T> void myMethod(T anyClassObject) {
    //handle code
}

My need is to create a method which will accept any class's instance. And then I have to save the object in database. actually I have to write a application which will make more easy the mongoTemplate API.

In my application user does not need to configure mongoTemplate. It all will be in my application. Users can simply use my code.

So 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 like

One one = new One();
createTable(one)

 or 

Two two = new Two();
createTable(two)

Would like to do it with generics.

3 Answers 3

1

you can do it this way

public <T> void myMethod(T anyClassObject) {

      //whatever you want to do
      if(anyClassObject instanceof ClassA){
           ClassA a=(ClassA)anyClassObject;
           //perform classA specific manipulations you want
      }
      //likewise for all the types you want to handle

}

it will accept any kind of object,and provide you the freedom you need.

Hope it helps!

good luck!

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

4 Comments

But I have to access the members of the object. I already tried all these methods. My objects are POJO/Bean classes. I have to manage my beans. But I could not found the member variables in object while debugging with any of these solutions.
you will have to do instanceOf check inside the method, to do your manipulations,editing my answer
I could not know which class is going on. Means ClassA is unknown.
for using generics you will definitely need to know which object you need to work with, else you can only use methods of Object class with generic object T
0

Generic creation of Java objects in a generic method can be done like this:

public class Test {

    public static void main(String[] args) {
        System.out.println(generateAndToString(A.class));
        System.out.println(generateAndToString(B.class));

        accessMemberWithReflection(new A());
        accessMemberWithReflection(new B());
    }

    public static <T> String generateAndToString(Class<T> clazz) {
        System.out.println(clazz.getName());
        try {
            T newInstance = clazz.newInstance();
            return newInstance.toString();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return "Something went wrong";
    }

    public static <T> void accessMemberWithReflection(T object) {
        try {
            Method declaredMethod = object.getClass().getDeclaredMethod("toString");
            String toStringOutput = (String) declaredMethod.invoke(object);
            System.out.println(toStringOutput);
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

-

public class A {
      @Override
      public String toString() {
            return "B";
      }
}

-

public class B {
      @Override
      public String toString() {
            return "B";
      }
}

-

4 Comments

But I have to access the members of the object. I already tried all these methods. My objects are POJO/Bean classes. I have to manage my beans. But I could not found the member variables in object while debugging with any of these solutions.
Does your object has a common interface or common super class... so you could access the methods or fields of the interface or the superclass
Another way to access the members of the beans would be with reflection... then you have to know the member names... do you have common members you would like to access?
to get the name of the class you can user clazz.getName()
0

You can try this code. are you looking for something else?

//test generic class
public class Test <T> {

public static void main(String[] args) {
    new Test<String>().testMethod("test");;
    new Test<Integer>().testMethod(1);;
    new Test<Long>().testMethod(10L);
}

//test method takes any object
public void testMethod(T obj){
    System.out.println(obj.getClass() + " " +obj);
}
}
}

To Access POJO methods

//test method takes any object
    public void testMethod(T obj){
        System.out.println(obj.getClass() + " " +obj);
        if(obj instance of YourPOJO){
           YourPOJO pojo = (YourPOJO )obj;
           System.out.println(pojo.getThing1());
        }
        if(obj instance of YourPOJO1){
           YourPOJO1 pojo1 = (YourPOJO1 )obj;
           System.out.println(pojo1.getThing1());
        }

    }
    }

4 Comments

But I have to access the members of the object. I already tried all these methods. My objects are POJO/Bean classes. I have to manage my beans. But I could not found the member variables in object while debugging with any of these solutions.
obj.getClass() will return java.lang.Class
Did you try running this example? It will give obj.getClass() as String/Integer/Long.. in your Case you all you have to do is new Test<YourPOJO>().testMethod(new YourPOJO());
You can never access the POJO bean class variables. At runtime only you will get to know what type the passed object is

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.