三、创建对象及反射机制

一、java获取对象的方式

 1、通过调用构造函数创建对象

 2、匿名对象的创建
 3、通过在类名前面指定包名来创建指定的对象
 4、通过反射机制来创建对象

A、通过调用Class.forName()来获取类名

Lattice lattice=(Lattice) Class.forName("com.lattice.java17_test.Lattice").newInstance();

Class classType=Class.forName("com.lattice.java17_test.Lattice");


B、通过调用类名.getClass()来获取类名

com.lattice.java17.Lattice lattice1=new com.lattice.java17.Lattice();
com.lattice.java17.Lattice lattice=lattice1.getClass().newInstance();

C、通过调用类名.class属性来获取类名

com.lattice.java17.Lattice lattice=com.lattice.java17.Lattice.class.newInstance();

D、通过loader()来动态获取类名

Person person=(Person)Proxy.newProxyInstance(Person.class.getClassLoader()
, new Class[]{Person.class}, new Maria(new Peter()));


//获取构造函数列表

Constructor[] constructor=classType.getConstructors();

//获取类属性列表

Field[] field = classType.getFields();

//获取方法wan

Method method=classType.getMethod("wan", null);
method.invoke(lattice, null);

//获取带参数和自定义类做参数的方法
A12 a=new A12();
Method method1=classType.getMethod("play",new Class[]{String.class,int.class,A12.class});
method1.invoke(lattice, new Object[]{"lattice",1,a});

//获取私有方法
Method method3=classType.getDeclaredMethod("test", null);
method3.setAccessible(true);
method3.invoke(lattice, null);

//获取私有属性
Field fieldName1 = classType.getDeclaredField("sex");
fieldName1.setAccessible(true);
String sex=(String) fieldName1.get(lattice);
System.out.println(sex);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值