一.Class部分
加载类的几种方式
// 1.
Class clazz = Class.forName("com.wzh.test.reflect.Person");
// 2.
Class clazz1 = new Person().getClass();
// 3.
Class clazz2 = Person.class;
// 4.
ClassLoader cl = ClassLoader.getSystemClassLoader();
Class clazz3 = cl.loadClass("com.wzh.test.reflect.Person");
获取加载器
ClassLoader cl = ClassLoader.getSystemClassLoader();
Class c = cl.loadClass("com.wzh.test.Student");
System.out.println(c);
System.out.println(c.getName());
////SSH的配置文件都是放在src(classpath)
//InputStream is= ClassLoader.getSystemResourceAsStream("user.properties");
//System.out.println(is);
//获取类对象
Class myc=Class.forName("com.wzh.test.Student");
System.out.println(myc);
//获取类实例,必须要有无参构造器
Student s= (Student)myc.newInstance();
System.out.println(s);
// 绝对路径
InputStream is = this.getClass().getResourceAsStream("/");
System.out.println(is);
// 相对路径
InputStream is2 = this.getClass().getResourceAsStream("a.xml");
System.out.println(is2);
// 相对路径
InputStream is3 = this.getClass().getResourceAsStream("b.xml");
System.out.println(is3);
//绝对路径 d:/test.xml
InputStream is4=new FileInputStream("d:/test.xml");
System.out.println(is4);
------------------------------------------------------------------------------
二.构造器部分
public static void main(String[] args) {
try {
Class c=Class.forName("com.wzh.test.Student");
//
try {
Constructor cs=c.getDeclaredConstructor(String.class,Integer.class);
Student stu=(Student)cs.newInstance("myname",123);
System.out.println(stu);
//获取所有构造器
Constructor[] css=c.getConstructors();
for (Constructor constructor : css) {
System.out.println(constructor);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
-----------------------------------------------
三.字段
public static void main(String[] args) throws Exception {
Class c = Class.forName("com.wzh.test.Student");
Student stu = (Student) c.newInstance();
Field[] fs = c.getDeclaredFields();
for (Field field : fs) {
System.out.println(field.getName());
if (!field.isAccessible())
field.setAccessible(true);
System.out.println(field.get(stu));
}
Field f = c.getDeclaredField("age");
if (!f.isAccessible())
f.setAccessible(true);
System.out.println("stu:" + f.get(stu));
}
---------------------------------------------------------
四.方法
public static void main(String[] args) throws Exception {
Class c = Class.forName("com.wzh.test.Student");
Student stu=(Student)c.newInstance();
Method m=c.getDeclaredMethod("play");
m.invoke(stu);
Method m2=c.getDeclaredMethod("play", String.class);
m2.invoke(stu, "依琳");
Method[] ms=c.getDeclaredMethods();
for (Method method : ms) {
System.out.println(method.getName());
}
}