当前位置:网站首页>反射的介绍
反射的介绍
2022-07-24 05:15:00 【x0757】
1.什么是反射?
反射是框架设计的灵魂,框架:它是一个半成品,可以拿来使用,添加上自己的业务代码。提高开发效率。
反射就是把类中成员抽取成其他类的过程。这就是反射。

2.如何获取反射类对象--Class
有三种:
(1) 通过Class.forName获取反射对象.
Class.forName("全路径") --spring它就是使用的该模式<bean class="全路径">(2)通过类名.class获取
类名.class; ---代理类--->SqlSession.getMapper(StudentDao.class)(3) 通过对象.getClass()方法获取
对象.getClass(); ---当知道对象时可以通过这种方式获取反射对象
public class Test01 {
public static void main(String[] args) throws ClassNotFoundException {
//1.通过Class.forName来获取反射类对象。
Class aClass = Class.forName("demo.People");
//2.通过类名调用.class获取反射类对象
Class aClass1 = People.class;
//3.通过对象获取反射类对象
People p=new People();
Class aClass2 = p.getClass();
//思考:上面三个反射对象的引用地址是否一致! 是一致的。 一个类只会被加在到内存中一次。
System.out.println(aClass==aClass1);
System.out.println(aClass2==aClass1);
}
}3.通过反射类获取对应的类对象。
public class Test02 {
public static void main(String[] args) throws IllegalAccessException, InstantiationException {
//1.获取反射类对象
Class<People> aClass = People.class;
//2.由反射类创建类对象---调用为无参构造函数
People people = aClass.newInstance();
People people2 = aClass.newInstance();
//3.他们的地址是否相同
System.out.println(people==people2);
}
}
4.通过反射获取对应的Field属性对象。
public class Test03 {
public static void main(String[] args) throws Exception {
Class<?> aClass = Class.forName("demo01.People");
//获取本类以及父类中指定的属性---必须为public修饰的。
Field sex = aClass.getField("sex");
System.out.println(sex);
//获取本类中指定的属性对象
Field name = aClass.getDeclaredField("name");
System.out.println(name);
//获取本类以及父类中所有public修饰的属性对象
Field[] fields = aClass.getFields();
for (Field field:
fields) {
System.out.println(field);
}
//获取本类中所有的属性对象
Field[] declaredFields = aClass.getDeclaredFields();
for (Field field:
declaredFields) {
System.out.println(field);
}
}
}4.2Field属性对象中常见的方法。
public class Test04 {
public static void main(String[] args) throws Exception{
Class<People> peopleClass = People.class;
//获取属性的名称
Field nameFiled = peopleClass.getDeclaredField("name");
String name = nameFiled.getName();
System.out.println(name);
//为属性赋值
People people = peopleClass.newInstance();
System.out.println(people);
nameFiled.setAccessible(true);
nameFiled.set(people,"王五");
System.out.println(people);
//获取属性值
Object o = nameFiled.get(people);
System.out.println(o);
}
}
5.通过反射获取对应的Method方法对象
public class Test05 {
public static void main(String[] args) throws Exception{
Class<People> peopleClass = People.class;
//获取本类以及父类中指定名称的方法对象
Method setName = peopleClass.getMethod("setName", String.class);
System.out.println(setName);
System.out.println("*******");
//获取本类和父类中所有public修饰的方法
Method[] methods = peopleClass.getMethods();
for (Method m :
methods) {
System.out.println(m);
}
System.out.println("+++++++");
//本类中指定的方法对象
Method fun = peopleClass.getDeclaredMethod("fun");
System.out.println(fun);
System.out.println("=========");
//获取本类中所有的方法。
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类中常见的方法
//method.invoke(对象,方法参数值);
System.out.println("-------");
People people = peopleClass.newInstance();
setName.invoke(people,"zhangsan");
System.out.println(people);
6.获取相应注解对象
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;
}
}
边栏推荐
- Mysq Database Constraints
- Chapter 1 regression, classification & clustering
- 1. Input a 100 point score from the keyboard and output its grade according to the following principles: score ≥ 90, Grade A; 80 ≤ score < 90, grade B; 70 ≤ score < 80, grade C; 60 ≤ score < 70, grade
- Use of fiddler packet capturing tool
- Ben, reducing online importance is the same. Abnormal instance CP operation found
- 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)
- 【NumPy】
- mapreduce概念
- Web3 product manager's Guide: how to face the encryption world
- )To feed back to the application layer or into multiple format documents:
猜你喜欢

Web3 product manager's Guide: how to face the encryption world

Recursive cascade network: medical image registration based on unsupervised learning

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

Chapter5 foundation of deep learning

Kingbase v8r6 cluster installation and deployment case - script online one click capacity reduction

This article takes you to understand C string functions and memory functions in simple terms

Basic knowledge of MySQL database

DNS domain name resolution service

MapReduce concept

Source code compilation!!
随机推荐
View progress!!! RPM installation!!!
C primer plus learning notes - 6. Arrays and pointers
Some thoughts about blogger coach soserious
Infineon launched the world's first TPM security chip with post quantum encryption technology for firmware update
13. Write a program, in which a user-defined function is used to judge whether an integer is a prime number. The main function inputs a number and outputs whether it is a prime number.
Illustration and text demonstrate the movable range of the applet movable view
2. Input a circle radius r, when r > = 0, calculate and output the area and perimeter of the circle, otherwise, output the prompt information.
【NumPy】
酒店IPTV数字电视系统解决方案
Hanoi problem
PSO and mfpso
1. Input a 100 point score from the keyboard and output its grade according to the following principles: score ≥ 90, Grade A; 80 ≤ score < 90, grade B; 70 ≤ score < 80, grade C; 60 ≤ score < 70, grade
Learning pyramid context encoder network for high quality image painting paper notes
pso和mfpso
Kingbase v8r6 cluster installation and deployment case - script online one click capacity reduction
Chapter5 foundation of deep learning
Codeforce:d2. remove the substring (hard version) [greedy string + subsequence]
Chapter III encog workbench
How to set up an internal wiki for your enterprise?
Introduction to 51 single chip microcomputer (dedicated to the most understandable article for beginners)