Java基础笔记14

1.反射.
Class:反射类 任何一个类都有一个Class反射类.(影子)
java.lang.reflect.*;
Field:字段类
Method:方法类类
Constructor:构造方法类.

2.获取反射类
//1.获取反射类 类名.class
Class clazz1=People.class;
//2.通过全类名
Class clazz2=Class.forName("demo.People");
//3.对象获取
People p=new People();
Class clazz3=p.getClass();
3.通过反射类实例化对应的类对象.
clazz.newInstance();

4.通过反射类获取类中的属性.
//获取父类或自己本类中public修饰的属性
Field ageField= clazz1.getField("age");
ageField.set(p, 156);
//只获取本类中自己声明的属性
Field nameField=clazz1.getDeclaredField("name");
nameField.setAccessible(true);//允许赋值
nameField.set(p, "张三");
System.out.println(p);
5.获取某个类的全部方法
Method showMethod= clazz1.getMethod("print",int.class);
//调用该方法
showMethod.invoke(p,15);

Method[] ms=clazz1.getDeclaredMethods();
for(Method m:ms){
System.out.println(Modifier.toString(m.getModifiers())+" "
+m.getReturnType().getName()+" "+m.getName()+"("+Arrays.asList(m.getGenericParameterTypes())+")");
}











转载于:https://www.cnblogs.com/qq634571685/p/6844929.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值