当前位置: 移动技术网 > IT编程>开发语言>Java > 通过Class类获取对象(实例讲解)

通过Class类获取对象(实例讲解)

2019年07月22日  | 移动技术网IT编程  | 我要评论

通过class对象获取对象的方式是通过class.newinstance()方式获取,通过调用默认构造参数实例化一个对象。

/**
 * created by hunt on 2017/6/27.
 * 测试的实体类
 * @data 编译后会自动生成set、get、无惨构造、equals、canequal、hashcode、tostring方法
 */
@data
public class person {
  private string name;
  private int age;
}
/**
 * created by hunt on 2017/6/27.
 */
public class newinstancetest {
  public static void main(string[] args) {
    class<person> personclass = person.class;//获取class实例
    try {
      person p = personclass.newinstance();//通过class获得person实例
      p.setage(28);
      p.setname("hunt");
      system.out.println(p);
    } catch (instantiationexception e) {
      e.printstacktrace();
    } catch (illegalaccessexception e) {
      e.printstacktrace();
    }
  }
}

提示:class.newinstance()是通过无参构造函数实例化的,一个对象默认是有一个无参构造函数,如果有一个有参构造函数,无参构造函数就不存在了,在通过反射获得对象会抛出 java.lang.instantiationexception 异常。

/**
 * created by hunt on 2017/6/27.
 * 测试的实体类
 */

public class person {
  private string name;
  private int age;

  public string getname() {
    return name;
  }

  public int getage() {
    return age;
  }

  public void setname(string name) {
    this.name = name;
  }

  public void setage(int age) {
    this.age = age;
  }

  public person(string name,int age){}//有参数构造函数
}
/**
 * created by hunt on 2017/6/27.
 */
public class newinstancetest {
  public static void main(string[] args) {
    class<person> personclass = person.class;//获取class实例
    try {
      person p = personclass.newinstance();//通过class获得person实例
      p.setage(28);
      p.setname("hunt");
      system.out.println(p.getage()+"----"+p.getname());
    } catch (instantiationexception e) {
      e.printstacktrace();
    } catch (illegalaccessexception e) {
      e.printstacktrace();
    }
  }
}

总结:以后创建实体类的时候一定要带上无参构造函数,以便以后使用反射的时候实例化对象不抛出异常。

以上这篇通过class类获取对象(实例讲解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网