Class 对象
package com.kuang.reflection;
//动态的创建对象,通过反射
public class Test09 {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
//获得Class 对象
Class c1 = Class.forName("com.kuang.reflection.User");
//构造一个对象,newInstance 调用的就是无惨构造器
User user = (User) c1.newInstance();
System.out.println(user);
}
}
Exception in thread "main" java.lang.InstantiationException: com.kuang.reflection.User
at java.lang.Class.newInstance(Class.java:427)
at com.kuang.reflection.Test09.main(Test09.java:11)
Caused by: java.lang.NoSuchMethodException: com.kuang.reflection.User.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.newInstance(Class.java:412)
... 1 more
通过构造器创建对象
package com.kuang.reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//动态的创建对象,通过反射
public class Test09 {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
//获得Class 对象
Class c1 = Class.forName("com.kuang.reflection.User");
//
// //构造一个对象,newInstance 调用的就是无惨构造器
// User user = (User) c1.newInstance();
// System.out.println(user);
//通过构造器创建对象
Constructor constructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
User user2 = (User) constructor.newInstance("秦僵", 001, 18);
System.out.println(user2);
//通过反射调用普通方法
User user3= (User) c1.newInstance();
//通过反射获取一个方法
Method setName = c1.getDeclaredMethod("setName", String.class);
//激活执行
//invoke: 激活的意思
//(对象,"方法的值")
setName.invoke(user3,"狂神");
System.out.println(user3.getName());
//通过反射操作属性
User user4= (User) c1.newInstance();
Field name = c1.getDeclaredField("name");
//不能操作私有属性,我们需要个关闭程序的安全检测,属性或者方法的setAccessible(true)
name.setAccessible(true); //取消安全检测,则能设置private 私有方法
name.set(user4,"狂神2");
System.out.println(user4.getName());
}
}
User{name=‘秦僵’, id=1, age=18}
狂神
狂神2
调用指定的方法
安全访问检查
package com.kuang.reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//分析性能问题
public class Test10 {
//普通方式调用
public static void test01(){
User user = new User();
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
user.getName();
}
long endTime = System.currentTimeMillis();
System.out.println("普通方式执行10亿次"+(endTime-startTime)+"ms");
}
//反射方式调用
public static void test02() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
Class c1 = user.getClass();
Method getName = c1.getDeclaredMethod("getName", null);
getName.setAccessible(false);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
getName.invoke(user,null);
}
long endTime = System.currentTimeMillis();
System.out.println("发射方式执行10亿次"+(endTime-startTime)+"ms");
}
//反射方式调用,关闭检查
//反射方式调用
public static void test03() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
Class c1 = user.getClass();
Method getName = c1.getDeclaredMethod("getName", null);
getName.setAccessible(true);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
getName.invoke(user,null);
}
long endTime = System.currentTimeMillis();
System.out.println("关闭方式执行10亿次"+(endTime-startTime)+"ms");
}
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
test01();
test02();
test03();
}
}
输出结果:
普通方式执行10亿次3ms
发射方式执行10亿次1711ms
关闭方式执行10亿次1165ms
反射操作泛型
package com.kuang.reflection;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
//通过反射获取泛型
public class Test11 {
public void test01(Map<String,User> map, List<User> list){
System.out.println("test01");
}
public Map<String,User> test02(){
System.out.println("test02");
return null;
}
public static void main(String[] args) throws NoSuchMethodException {
//入参:方法名,Map 入参,List 入参
Method method = Test11.class.getMethod("test01", Map.class, List.class);
//获得泛型的参数类型
Type[] genericParameterTypes = method.getGenericParameterTypes();
//获取参数类型里面的泛型
//genericParameterTypes:参数化类型
for (Type genericParameterType : genericParameterTypes) {
//打印他的类型
System.out.println("#"+genericParameterType);
//想知道里面的类型
//父类子类
if(genericParameterType instanceof ParameterizedType){
Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArgument);
}
}
}
method = Test11.class.getMethod("test02",null);
Type genericReturnType = method.getGenericReturnType();
if(genericReturnType instanceof ParameterizedType){
Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArgument);
}
}
}
}
输出结果:
#java.util.Map<java.lang.String, com.kuang.reflection.User>
class java.lang.String
class com.kuang.reflection.User
#java.util.List<com.kuang.reflection.User>
class com.kuang.reflection.User
class java.lang.String
class com.kuang.reflection.User
反射操作注解
对象关系映射,获取注解里面的值
package com.kuang.reflection;
import java.lang.annotation.*;
import java.lang.reflect.Field;
//练习反射操作注解
public class Test13 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class c1 = Class.forName("com.kuang.reflection.Student2");
//通过反射获得注解
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
//获得注解的value 的值
Tablekuang tablekuang = (Tablekuang) c1.getAnnotation(Tablekuang.class);
String value = tablekuang.value();
System.out.println(value);
//获得类指定的注解
Field f = c1.getDeclaredField("name");
Filedkuang annotation = f.getAnnotation(Filedkuang.class);
System.out.println(annotation.columnName());
System.out.println(annotation.type());
System.out.println(annotation.length());
}
}
@Tablekuang(value="db_student")
class Student2{
@Filedkuang(columnName = "db_id",type="int",length =10)
private int id;
@Filedkuang(columnName = "db_age",type="int",length =10)
private int age;
@Filedkuang(columnName = "db_name",type="varchar",length =3)
private String name;
public Student2() {
}
public Student2(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
@Override
public String toString() {
return "Student2{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
'}';
}
}
//类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Tablekuang{
String value();
}
//属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Filedkuang{
String columnName();
String type();
int length();
}