简体   繁体   English

具有任何类对象的方法参数的Java泛型

[英]Java generics for method parameter with any class object

I have a Java method which has to accept generic object. 我有一个Java方法,必须接受通用对象。

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. 所以请帮助我使用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: 只需使用Object作为类型:

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 . doNothing("").length()将编译 - 如果doNothing传递一个String ,则它返回一个String

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM