【问题标题】:Generic class, calling generic class with clone泛型类,用克隆调用泛型类
【发布时间】:2018-03-26 12:09:53
【问题描述】:

我需要用实现cloneable 来创建一个泛型类,为此我需要执行该类的克隆方法和另一个方法来获取此方法。 老师在房间里通过了它,但没有工作并给出方法错误。我该怎么办?

  public class Deposito <X> implements Cloneable {
       public Object clone () {
           Deposito ret=null;

           try {
               ret = new Deposito (this);
           }
           catch (Exception erro) { 
           } 
        return ret;
      }

      private X meuCloneDeX (X x) {
          X ret = null;

          try {
              Class<?> classe = x.getClass();
              Class<?>[] tipoDoParametroFormal = null; 
              Method metodo = classe.getMethod ("clone", tipoDoParametroFormal);
              Object[] parametroReal = null;// pq clone tem 0 parametros
              ret = ((X)metodo.invoke (x, parametroReal));
          }
          catch (NoSuchMethodException erro)
          {}
          catch (InvocationTargetException erro)
          {}
          catch (IllegalAccessException erro)
          {}

          return ret;
       }
}

错误 - 找不到符号:

Method metodo = classe.getMethod("clone", tipoDoParametroFormal);

【问题讨论】:

  • 传入的是什么对象?它实际上有一个公共的clone 方法吗?

标签: java invoke cloneable getmethod


【解决方案1】:

也许你应该使用Class#getDeclaredMethod。因为你刚刚“声明”了你的克隆方法......如果它为空时忽略这个方法的第二个参数会更好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 2021-03-28
    • 2022-10-14
    • 1970-01-01
    • 2019-07-21
    相关资源
    最近更新 更多