您的位置:首页 > 编程语言 > Java开发

JAVA:认识理解Java中的native方法

2014-06-27 16:18 162 查看
今天在看ArrayList的java源码时看到,其中的一个public Object clone()克隆方法:

/**
* Returns a shallow copy of this <tt>ArrayList</tt> instance.  (The
* elements themselves are not copied.)
*
* @return a clone of this <tt>ArrayList</tt> instance
*/
public Object clone() {
try {
@SuppressWarnings("unchecked")
ArrayList<E> v = (ArrayList<E>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}
其使用的是:Arrays.copyof其源代码为:
public static <T> T[] copyOf(T[] original, int newLength) {
return (T[]) copyOf(original, newLength, original.getClass());
}
然后跟踪下copyof:
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}

最终的copyof实现时System.arraycopy实现的,找到java.lang.System中的arraycofy,看到该方法只有一个声明:
public static native void arraycopy(Object src,  int  srcPos,
Object dest, int destPos,
int length);
却没有对应的实现,但是有个标志:native,说明该方法是个扩展方法,是使用C/C++语言实现的,并且编译成了dll文件,然后由java去
调用,这也是java的底层机制, 实际上java就是在不同的平台上调用不同的native方法实现对操作系统的访问的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: