当前位置:网站首页>Introduction to reflection
Introduction to reflection
2022-07-24 05:21:00 【x0757】
1. What is reflection ?
Reflection is the soul of frame design , frame : It's a semi-finished product , It can be used , Add your own business code . Improve development efficiency .
Reflection is the process of extracting members from a class into other classes . This is reflection .

2. How to get reflection class objects --Class
There are three kinds of :
(1) adopt Class.forName Get the reflection object .
Class.forName(" The full path ") --spring It is the mode used <bean class=" The full path ">(2) By class name .class obtain
Class name .class; --- proxy class --->SqlSession.getMapper(StudentDao.class)(3) Through object .getClass() Method to get
object .getClass(); --- When you know the object, you can get the reflection object in this way
public class Test01 {
public static void main(String[] args) throws ClassNotFoundException {
//1. adopt Class.forName To get reflection class objects .
Class aClass = Class.forName("demo.People");
//2. Called by the class name .class Get the reflection class object
Class aClass1 = People.class;
//3. Get reflection class objects through objects
People p=new People();
Class aClass2 = p.getClass();
// reflection : Whether the reference addresses of the above three reflection objects are consistent ! It's consistent . A class will only be added to memory once .
System.out.println(aClass==aClass1);
System.out.println(aClass2==aClass1);
}
}3. Get the corresponding class object through the reflection class .
public class Test02 {
public static void main(String[] args) throws IllegalAccessException, InstantiationException {
//1. Get the reflection class object
Class<People> aClass = People.class;
//2. Create class objects from reflection classes --- Call a parameterless constructor
People people = aClass.newInstance();
People people2 = aClass.newInstance();
//3. Are their addresses the same
System.out.println(people==people2);
}
}
4. Get the corresponding... Through reflection Field Property object .
public class Test03 {
public static void main(String[] args) throws Exception {
Class<?> aClass = Class.forName("demo01.People");
// Get the attributes specified in this class and its parent class --- It has to be for public Embellished .
Field sex = aClass.getField("sex");
System.out.println(sex);
// Get the property object specified in this class
Field name = aClass.getDeclaredField("name");
System.out.println(name);
// Get all in this class and its parent class public Decorated property object
Field[] fields = aClass.getFields();
for (Field field:
fields) {
System.out.println(field);
}
// Get all property objects in this class
Field[] declaredFields = aClass.getDeclaredFields();
for (Field field:
declaredFields) {
System.out.println(field);
}
}
}4.2Field Common methods in attribute objects .
public class Test04 {
public static void main(String[] args) throws Exception{
Class<People> peopleClass = People.class;
// Gets the name of the property
Field nameFiled = peopleClass.getDeclaredField("name");
String name = nameFiled.getName();
System.out.println(name);
// Assign values to properties
People people = peopleClass.newInstance();
System.out.println(people);
nameFiled.setAccessible(true);
nameFiled.set(people," Wang Wu ");
System.out.println(people);
// Get attribute value
Object o = nameFiled.get(people);
System.out.println(o);
}
}
5. Get the corresponding... Through reflection Method Method object
public class Test05 {
public static void main(String[] args) throws Exception{
Class<People> peopleClass = People.class;
// Get the method object with the specified name in this class and its parent class
Method setName = peopleClass.getMethod("setName", String.class);
System.out.println(setName);
System.out.println("*******");
// Get all in this class and parent class public The method of decoration
Method[] methods = peopleClass.getMethods();
for (Method m :
methods) {
System.out.println(m);
}
System.out.println("+++++++");
// The method object specified in this class
Method fun = peopleClass.getDeclaredMethod("fun");
System.out.println(fun);
System.out.println("=========");
// Get all the methods in this class .
Method[] declaredMethods = peopleClass.getDeclaredMethods();
for (Method m:declaredMethods
) {
System.out.println(m);
}
System.out.println("-------");
People people = peopleClass.newInstance();
setName.invoke(people,"zhangsan");
System.out.println(people);
}
}
5.2 Method Class
//method.invoke( object , Method parameter value );
System.out.println("-------");
People people = peopleClass.newInstance();
setName.invoke(people,"zhangsan");
System.out.println(people);
6. Get the corresponding annotation object
TableFiled tableField = declaredField.getAnnotation(TableFiled.class);
public int insert(T t){
try{
StringBuffer sb = new StringBuffer("insert into ");
Class<?> aClass = t.getClass();
TableName annotation = aClass.getAnnotation(TableName.class);
String tableName ="";
if(annotation!=null){
tableName = annotation.value();
}else {
tableName = aClass.getSimpleName();
}
sb.append(tableName);
System.out.println(sb);
Field[] declaredFields = aClass.getDeclaredFields();
List<String> columns = new ArrayList<>();
List<String> values = new ArrayList<>();
for (Field declaredField:declaredFields){
declaredField.setAccessible(true);
TableFiled tableField = declaredField.getAnnotation(TableFiled.class);
if(tableField!=null){
columns.add(tableField.value());
}else {
columns.add(declaredField.getName());
}
values.add("'"+declaredField.get(t)+"'");
}
sb.append(columns.toString().replace("[","(").replace("]",")"));
sb.append(" values ");
sb.append(values.toString().replace("[","(").replace("]",")"));
System.out.println(sb);
Connection conn = DBUtils.getConn();
PreparedStatement ps = conn.prepareStatement(sb.toString());
int i = ps.executeUpdate();
return i;
}catch (Exception e){
e.printStackTrace();
}finally {
DBUtils.closeAll(rs,ps,connection);
}
return 0;
}
}
边栏推荐
- PPPoE网关模拟环境搭建
- Pointer learning diary (IV) use structure and pointer (linked list)
- 【sklearn】RF 交叉验证 袋外数据 参数学习曲线 网格搜索
- Image painting for irregular holes using partial revolutions paper notes
- Handwritten ORM framework
- 1、基于增量式生成遮挡与对抗抑制的行人再识别
- Data annotation learning summary
- 纯小白教程 在idea里使用Druid数据库连接池
- MySQL insight
- 反射
猜你喜欢

Performance test process

太空可再生能源的代币化

AttributeError: ‘NoneType‘ object has no attribute ‘shape‘

JMeter FAQs

Ren Xudong, chief open source liaison officer of Huawei: deeply cultivate basic software open source and jointly build the root technology of the digital world
![Embedded system transplantation [3] - uboot burning and use](/img/36/69daec5f1fe41bd3d0433d60816bba.png)
Embedded system transplantation [3] - uboot burning and use

FRP intranet penetration service usage

Beginners' preparation for the Blue Bridge Cup (University Programming learning history records, topic ideas for students who need to prepare for the Blue Bridge Cup)

jdbc封装一个父类减少代码重复

DNS domain name resolution service
随机推荐
Beginners' preparation for the Blue Bridge Cup (University Programming learning history records, topic ideas for students who need to prepare for the Blue Bridge Cup)
Source code compilation!!
明星逆市入局的NFT,如何能走出独立行情?
7. Find the sum of numbers between 100 and 300 that can be divided by 3.
模拟加法 & 结构体基本用法
Data annotation learning summary
The world's first large aerospace model came out. Wenxin's second supplement "Fuchun Mountain Residence map" is Baidu Pratt Whitney AI's perseverance
C primer plus learning notes - 6. Arrays and pointers
使用d2l包和相关环境配置的一些血泪心得
Installation and login login
Bear market bottoming Guide
On the dilemma faced by non transferable reputation points NFT SBTS
反射的介绍
1. There is a fractional sequence: 2/1, 3/2, 5/3, 8/5, 13/8,... Program to sum the first 20 items of this sequence.
Create and delete databases using databases
Ia notes 2
Drools development decision table
Chapter5 foundation of deep learning
Numpy statistical correlation function example tutorial
DHCP principle and configuration