Java 泛型类,使用克隆调用泛型类
我需要用implementsJava 泛型类,使用克隆调用泛型类,java,invoke,cloneable,getmethod,Java,Invoke,Cloneable,Getmethod,我需要用implementscloneable创建一个泛型类,为了实现这一点,我需要对该类执行一个clone方法,并使用另一个方法获得该方法。 老师在教室里传递了它,但没有工作,并且给出了错误的方法。我该怎么办 public class Deposito <X> implements Cloneable { public Object clone () { Deposito ret=null; try {
cloneable
创建一个泛型类,为了实现这一点,我需要对该类执行一个clone方法,并使用另一个方法获得该方法。
老师在教室里传递了它,但没有工作,并且给出了错误的方法。我该怎么办
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;
}
}
公共类存款实现可克隆{
公共对象克隆(){
存款利息=空;
试一试{
ret=新存款(本);
}
捕获(异常错误){
}
返回ret;
}
私人X meuCloneDeX(X X){
X ret=null;
试一试{
Class classe=x.getClass();
类[]tipoDoParametroFormal=null;
方法metodo=classe.getMethod(“克隆”,tipoDoParametroFormal);
Object[]parametroReal=null;//pq克隆tem 0 parametros
ret=((X)metodo.invoke(X,parametroReal));
}
捕获(NoSuchMethodException错误)
{}
捕获(InvocationTargetException错误)
{}
捕获(非法访问异常错误)
{}
返回ret;
}
}
错误-找不到符号:
方法metodo=classe.getMethod(“克隆”,tipoDoParametroFormal) 也许你应该使用
Class#getDeclaredMethod
。因为你刚刚“声明”了你的克隆方法…最好在这个方法的第二个参数为空时忽略它 传入什么类型的对象?它实际上有公共的克隆方法吗?