JAVA_数组

package com.kk.array;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;


public class ArrayTest {

public static void main(String[] args) throws Exception{
dynamicGetInstance("com.kk.array.P");
}

/*
* 数组拷贝
*/
static void arrayCopy(){
int []num1={1,2,3};
int []num2=new int[3];
System.arraycopy(num1, 0, num2, 0, 3);
for (int i = 0; i < num2.length; i++) {
System.out.println(num2[i]);
}
}

/*
* 获取Class
*/
static void getClassName() throws ClassNotFoundException{
P p=new P(1,2);
Class c1=p.getClass();
System.out.println(c1.getName());
Class c2=Class.forName("com.kk.array.P");
System.out.println(c2.getName());
Class c3=P.class;
System.out.println(c3.getName());
Class c4=int.class;
System.out.println(c4.getName());
Class c5=Integer.TYPE;
System.out.println(c5.getName());
}

/*
* 通过反射调用类的方法
*/
static void dynamicGetInstance(String className) throws Exception{
P c=(P) Class.forName(className).newInstance();
//Method [] method=c.getClass().getMethods();得到类中所有方法,包括private修饰的
Constructor[] structs=c.getClass().getDeclaredConstructors();//得到公共的方法
Constructor struct=structs[1];
Class[] types=struct.getParameterTypes();
Object[] paramValues=new Object[types.length];
for (int i = 0; i < types.length; i++) {
paramValues[i]=i+1;
}
Object o=struct.newInstance(paramValues);
Method[] methods=c.getClass().getDeclaredMethods();
for(Method method:methods){
Long result=(Long) method.invoke(o, null);
System.out.println("结果:"+result);
}
}
}
class P{
private int x,y;

public P() {
super();
}

public P(int x, int y) {
this.x = x;
this.y = y;
}

public long add(){
return x+y;
}
}
原文地址:https://www.cnblogs.com/BigIdiot/p/2299445.html