处理 `Array.clone()` 没有通过反射出现

Dealing with `Array.clone()` not showing up via reflection

我正在编写一个库,我想在其中查找在特定 class 上具有特定名称的方法并将其保存以备后用。我是通过反思这样做的:

public static Method findMethod(Class<?> instance_c, String name, Class<?> ... args_cs) {
    return instance_c.getMethod(name, args_cs);
}

现在的问题如下:

    Class<?> c = int[].class;
    // int[] i = new int[2].clone();
    System.out.println(findMethod(c, "clone")); // Throws an exception

这是有记录的行为:

Method java.lang.Class.getMethod(String name, Class... parameterTypes):

[snip]

If this Class object represents an array type, then this method does not find the clone() method.


有什么方法可以让我仍然可以将 java.lang.reflect.Method 的功能与 Array#clone 一起使用?我可以想象一个内置的或自己编写的 Proxie,它可以让我在这种特殊情况下保留 Method 的功能。

如果我要进一步解释我特别使用的 Method 是什么,请发表评论。目标是尽可能多地保留。

作为一个 class,数组 classes 有点奇怪并且没有很多有用的方法依赖于 helper classes 因为它们没有在不改变语言的情况下有任何扩展方式。

Object.clone() 方法可用。

public static void main(String[] args) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
    for(Method m : int[].class.getDeclaredMethods())
        System.out.println(m);
    for(Method m : int[].class.getSuperclass().getDeclaredMethods())
        System.out.println(m);
    Method clone = int[].class.getSuperclass().getDeclaredMethod("clone");
    clone.setAccessible(true);
    int[] ints = { 1,2,3 };
    int[] ints2 = (int[]) clone.invoke(ints);
    System.out.println(Arrays.toString(ints2));
}

打印

protected void java.lang.Object.finalize() throws java.lang.Throwable
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang.Object)
public java.lang.String java.lang.Object.toString()
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
protected native java.lang.Object java.lang.Object.clone() throws java.lang.CloneNotSupportedException
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
private static native void java.lang.Object.registerNatives()
[1, 2, 3]

更简单地说,您可以在任何对象上使用 Object.clone() 使其可访问。