通过class对象获取对象的方式是通过class.newinstance()方式获取,通过调用默认构造参数实例化一个对象。
1 /** 2 * created by hunt on 2017/6/27.
* 测试的实体类 4
* @data 编译后会自动生成set、get、无惨构造、equals、canequal、hashcode、tostring方法 5
*/ 6 @data 7 public class person { 8 private string name; 9
private int age;10 }
1 /** 2 * created by hunt on 2017/6/27. 3
*/ 4 public class newinstancetest { 5 public static void main(string[] args) { 6
class<person> personclass = person.class;//获取class实例 7 try { 8
person p = personclass.newinstance();//通过class获得person实例 9
p.setage(28);10 p.setname(hunt);11
system.out.println(p);12 } catch (instantiationexception e) {13
e.printstacktrace();14 } catch (illegalaccessexception e) {15
e.printstacktrace();16 }17 }18 }
提示:class.newinstance()是通过无参构造函数实例化的,一个对象默认是有一个无参构造函数,如果有一个有参构造函数,无参构造函数就不存在了,在通过反射获得对象会抛出 java.lang.instantiationexception 异常。
1 /** 2 * created by hunt on 2017/6/27. 3
* 测试的实体类 4 */ 5 6 public class person { 7 private string name; 8
private int age; 9 10 public string getname() {11 return name;12 }13 14
public int getage() {15 return age;16 }17 18 public void setname(string name) {19
this.name = name;20 }21 22 public void setage(int age) {23 this.age = age;24 }25 26
public person(string name,int age){}//有参数构造函数27 }
1 /** 2 * created by hunt on 2017/6/27. 3 */ 4 public class newinstancetest { 5
public static void main(string[] args) { 6 class<person> personclass = person.class;//获取class实例 7
try { 8 person p = personclass.newinstance();//通过class获得person实例 9
p.setage(28);10
p.setname(hunt);11 system.out.println(p.getage()+----+p.getname());12 }
catch (instantiationexception e) {13 e.printstacktrace();14 }
catch (illegalaccessexception e) {15 e.printstacktrace();16 } }
}
总结:以后创建实体类的时候一定要带上无参构造函数,以便以后使用反射的时候实例化对象不抛出异常。
以上就是通过class类获取对象详解的详细内容。