创建对象的方式
//创建对象1:new
//创建对象2:clone
//创建对象3:序列化(序列化会引发安全漏洞,未来将会被移除jdk)
//创建对象4:反射 动态性 字符串
public class CreateNewObj implements Cloneable{
public void hello() {
System.out.println("hello world");
}
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String[] args) throws CloneNotSupportedException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
//new和克隆
CreateNewObj test = new CreateNewObj();
test.hello();
CreateNewObj clone = (CreateNewObj) test.clone();//内存中位置不一样 深度克隆和浅克隆?
clone.hello();
//反射
Class<?> cloneClass = Class.forName("reflect.CreateNewObj");
Object o = cloneClass.newInstance();
cloneClass.getMethod("hello").invoke(o);
}
}
反射常用方法
public class ReflectTest {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException {
//获取Class方法
Class s1 = Class.forName("reflect.Student");
Class s2 = Student.class;
Student student = new Student("hello");
Class s3 = student.getClass();
//常用方法
for (Field f : s3.getDeclaredFields()) {
f.setAccessible(true); //private->public 临时的
System.out.println(f.getName() + ":" + f.get(student));
}
System.out.println(Arrays.toString(s1.getConstructors())); //Construct.getParameterCount获取参数
System.out.println(Arrays.toString(s1.getDeclaredFields()));//获取自身声明的变量,包括私有变量(getFields获取自身和父类public字段)
System.out.println(Arrays.toString(s1.getDeclaredMethods()));//获取自身声明的方法(不包括父类) m.invoke(obj,args) 不是静态的就要传具体对象
System.out.println(s1.getModifiers());//修饰符?
System.out.println(s1.getSuperclass().getName());//父类
System.out.println(Arrays.toString(s1.getInterfaces()));//实现的接口
System.out.println(s1.getPackage().getName());//所属包
System.out.println(Arrays.toString(s1.getAnnotations()));//获取注解
}
}
class Student implements Cloneable {
private String name;
private int id;
public Student(String name) {
this.name = name;
}
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public void hello() {
System.out.println("hello world");
}
}
反射的应用 - 数组长度拓展
public class ArrayLenExtend {
public static Object goodCopy(Object oldArray, int newLength) {
//Array类型
Class c = oldArray.getClass();
System.out.println(c.getName());
//元素类型
Class componentType = c.getComponentType();
System.out.println(componentType.getName());
//创建新数组
Object newArray = Array.newInstance(componentType, newLength);
//拷贝
int oldLength = Array.getLength(oldArray);
System.arraycopy(oldArray, 0, newArray, 0, oldLength);
//返回
return newArray;
}
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5};
a = (int[]) goodCopy(a,10);
System.out.println(a.length);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。