本帖最后由 游呤人 于 2015-7-16 01:32 编辑
加载Class的方法
类名.class
实例.getclass
Class.forname(类的全路径名) //com.XXX.类名,这种方法以后会比较常见,
//比如在与数据库通信时加载JDBC的方法.也是比较推荐大家使用的
获得构造器级创建实例.
两步走,
一获得加载类的class方法见上面,
二获得构造器
获得构造器有两中方法,
class.getConstructor(class.. c)|class.getConstructor() 返回Constructor
class.. c 表示程序该程序参数列表,程序会自动匹配,类型相同的参数列表不写参数列表表示,程序无参构造
class.getConstructors() 返回Constructors
但是这种方法只能返回public的构造参数- package com.refect;
- @SuppressWarnings("all")
- public class Student {
- private String name;
- private int age;
- private int yuWen;
- private int shuXue;
- private int yingYu;
- static {
- System.out.println("你好");
- }
- protected Student(){}
- /* private Student() {
- }*/
- public Student(String name, int yuWen, int shuXue, int yingYu) {
- this.name = name;
- this.yuWen = yuWen;
- this.yingYu = yingYu;
- this.shuXue = shuXue;
- }
- public Student(String name) {
- this.name = name;
- }
- public Student(String name, int age) {
- this.name = name;
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public void setyuWen(int yuWen) {
- this.yuWen = yuWen;
- }
- public int getyuWen() {
- return yuWen;
- }
- public void setyingYu(int yingYu) {
- this.yingYu = yingYu;
- }
- public int getyingYu() {
- return yingYu;
- }
- public String toString() {
- return name +'\t' + yuWen + '\t' + shuXue + '\t' + yingYu + '\t'
- + getSum()+"\t age:"+age;
- }
- public int getSum() {
- return yuWen + shuXue + yingYu;
- }
- private void hop(){
- System.out.println("加油");
- }
- }
复制代码- public class RefectDome {
- public static void main(String[] args) throws Exception {
- Class studentClazz = Class.forName("com.refect.Student");
- Constructor[] conArr = studentClazz.getDeclaredConstructors();
-
- for (Constructor constructor : conArr) {
- System.out.println(constructor);
- }
- System.out.println("-------------------------------------");
- Constructor con = studentClazz.getConstructor(String.class, int.class,
- int.class, int.class);
- System.out.println(con);
- Object o = con.newInstance("张三", 18, 79, 89);
- System.out.println(o);
- Student stu= (Student) studentClazz.newInstance();
- System.out.println(stu);
- }
- }
复制代码
|
|