简体   繁体   English

Java中以对象为参数的泛型方法

[英]Generic Method with object as argument in Java

There are two classes A and B which have similar methods. 有两个类A和B具有相似的方法。 How to write a generic method that takes either one of the class object as argument and will be able to call the methods of that class. 如何编写一个以类对象之一作为参数并可以调用该类方法的通用方法。

Edit : I do not have control over class A, B. I get them only as arguments. 编辑:我没有对类A,B的控制。我只能将它们作为参数。 So i cannot modify add them. 所以我不能修改添加它们。

public class methods {

    public static void main(String[] args) {
        new methods().getName(new B());
        new methods().getName(new A());
    }

    private <T> void getName(T obj){
        // obj.getName()
    }
}

class A {

    String name = "ClassA";

    public void getName(){
        System.out.println(name);
    }

}

class B {

    String name = "ClassB";

    public void getName(){
        System.out.println(name);
    }

}

If the two classes do not implement a common interface, you could use reflection, but this is not type safe (you won't get any compilation errors if A or B no longer support getName() and reflection is much slower than calling a method directly. 如果两个类未实现公共接口,则可以使用反射,但这不是类型安全的(如果A或B不再支持getName() ,则不会出现任何编译错误,并且反射比调用方法慢得多)直。

You could also implement two adapters that share an interface and use those (with generics): 您还可以实现两个适配器,它们共享一个接口并使用它们(与泛型一起使用):

interface Wrapper {
    String getName();
}

class WrapperA implements Wrapper {
    final private A a;
    public WrapperA(A wrapped) {
        this.a = wrapped;
    }
    @Override public String getName() {
        return a.getName();
    }
}

Below solution uses instanceof operator in the generic method to reach your output. 下面的解决方案在通用方法中使用instanceof operator来获取您的输出。

   public static void main(String[] args){
        new methods().getName(new B());
        new methods().getName(new A());
    }

    private <T> void getName(T obj) {
        if(obj instanceof B){
            ((B) obj).getName();
        }
        else{
            ((A) obj).getName();
        }
    }

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

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