java 反射

反射

package model;
import java.lang.reflect.*;
import java.util.Date;
public class Person {
public static void main(String[] args) throws Exception {
Class personClass = Person.class;
Object instance = personClass.newInstance();
System.out.println("*****************获取公有、无参的构造方法*************");
Constructor con = personClass.getConstructor(null);
//1>、因为是无参的构造方法所以类型是一个null,不写也可以:这里需要的是一个参数的类型,切记是类型
//2>、返回的是描述这个无参构造函数的类对象。
System.out.println("*************获取公有字段**并调用*****************");
Field f = personClass.getField("age");
System.out.println(f);
System.out.println("*************获取公有方法并调用*****************");
Method m2 = personClass.getMethod("sayHello2", String.class);
Object invoke = m2.invoke(instance, new String[]{" aaa"});
System.out.println(invoke);
System.out.println("***************获取私有的方法******************");
Method m3 = personClass.getDeclaredMethod("sayHello3", String.class);
m3.setAccessible(true);
Object invoke1 = m3.invoke(instance, new String[]{"vvv"});
System.out.println(invoke1);
}
private Integer id;
private String name;
private Integer sex;
private Date birth;
public int age;
public Person() {
}
public Person(Integer id, String name, Integer sex, Date birth, int age) {
this.id = id;
this.name = name;
this.sex = sex;
this.birth = birth;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void sayHello() {
System.out.println("hello");
}
public String sayHello2(String name) {
return "hello" + name;
}
private String sayHello3(String name) {
return "hello " + name;
}
}
posted @   一只桔子2233  阅读(65)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示