package com.qiaoyx.java2;
import com.qiaoyx.java1.Person;
import com.sun.org.apache.xpath.internal.objects.XStringForFSB;
import org.junit.Test;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
/**
* 获取当前运行时类的所有属性
*
* @author: qyx
* @date: 2022-08-17 11:26
* @desc:
*/
public class FieldTest {
@Test
public void test1() {
Class clazz = Person.class;
//获取属性结构
//getFields()获取运行时类和它的父类权限是public的所有属性
Field[] fields = clazz.getFields();
for (Field field : fields) {
System.out.println(field);
}
System.out.println();
//getDeclaredFields():获取当前运行时类中声明的所有属性。(不包含父类中声明的属性)
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field : declaredFields) {
System.out.println(field);
}
}
//权限修饰符 数据类型 变量名
@Test
public void test2() {
Class clazz = Person.class;
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field : declaredFields) {
//1.权限修饰符
int modifier = field.getModifiers();
System.out.print(Modifier.toString(modifier) + "\t");
//2.数据类型
Class type = field.getType();
System.out.print(type.getName() + "\t");
//3.变量名
String name = field.getName();
System.out.println(name);
System.out.println();
}
}
}
package com.qiaoyx.java2;
import com.qiaoyx.java1.Person;
import org.junit.Test;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* 获取运行时类的方法结构
*
* @author: qyx
* @date: 2022-08-17 16:01
* @desc:
*/
public class MethodTest {
@Test
public void test1() {
Class<Person> clazz = Person.class;
//获取运行时类和父类所有public方法
Method[] methods = clazz.getMethods();
for (Method method : methods) {
System.out.println(method);
}
System.out.println();
//获取当前运行时类中的所有方法(不包含父类中声明的方法)
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method method : declaredMethods) {
System.out.println(method);
}
}
/*
@Xxxx
权限修饰符 返回值类型 方法名(参数类型1,形参名1....) throws XxxException{}
*/
@Test
public void test2() {
Class<Person> clazz = Person.class;
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method method : declaredMethods) {
//1.获取方法声明的注解
Annotation[] annotations = method.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
//2.权限修饰符
System.out.print(Modifier.toString(method.getModifiers()) + "\t");
//3.返回值类型
System.out.print(method.getReturnType().getName() + "\t");
//4.方法名
System.out.print(method.getName());
System.out.print("(");
//5.形参列表
Class[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length > 0) {
for (Class p : parameterTypes) {
System.out.print(p.getName());
}
for (int i = 0; i < parameterTypes.length; i++) {
if (i == parameterTypes.length - 1) {
System.out.print(parameterTypes[i] + " args_" + i);
} else {
System.out.print(parameterTypes[i] + " args_" + i + ",");
}
}
}
System.out.println(")");
//6.抛出的异常
Class[] exceptionTypes = method.getExceptionTypes();
if(!(exceptionTypes == null && exceptionTypes.length == 0)){
System.out.println("throws ");
for (int i = 0;i < exceptionTypes.length;i++){
if(i == exceptionTypes.length - 1){
System.out.print(exceptionTypes[i].getName());
break;
}
System.out.print(exceptionTypes[i].getName() + ",");
}
}
}
}
}
package com.qiaoyx.java2;
import com.qiaoyx.java1.Person;
import org.junit.Test;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
/**
*
* 获取构造器结构
* @author: qyx
* @date: 2022-08-17 18:24
* @desc:
*/
public class OtherTest {
@Test
public void test1(){
Class<Person> clazz = Person.class;
//getConstructors():获取当前运行时类中声明为public的构造器
Constructor[] constructors = clazz.getConstructors();
for(Constructor constructor : constructors){
System.out.println(constructor);
}
System.out.println();
//获取当前运行时类中所有构造器
Constructor[] declaredConstructors = clazz.getDeclaredConstructors();
for(Constructor constructor : declaredConstructors){
System.out.println(constructor);
}
}
/*
获取运行时类的父类
*/
@Test
public void test2(){
Class clazz = Person.class;
Class superclass = clazz.getSuperclass();
System.out.println(superclass);
}
/*
获取运行时类的带泛型的父类
*/
@Test
public void test3(){
Class clazz = Person.class;
Type genericSuperclass = clazz.getGenericSuperclass();
System.out.println(genericSuperclass);
}
/*
获取运行时类的带泛型父类的泛型类型
代码:逻辑性代码(强调实现过程) vs 功能性代码(直接用)
*/
@Test
public void test4(){
Class clazz = Person.class;
Type genericSuperclass = clazz.getGenericSuperclass();
ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
//获取泛型参数
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
System.out.println(actualTypeArguments[0].getTypeName());
System.out.println(((Class)(actualTypeArguments[0])).getName());
}
/*
获取运行时类实现的接口
*/
@Test
public void test5(){
Class clazz = Person.class;
Class[] interfaces = clazz.getInterfaces();
for (Class c : interfaces){
System.out.println(c);
}
//获取运行时类父类的接口
Class[] interfaces1 = clazz.getSuperclass().getInterfaces();
for (Class c : interfaces1){
System.out.println(c);
}
}
/*
获取当前运行时类所在的包
*/
@Test
public void test6(){
Class clazz = Person.class;
Package pack = clazz.getPackage();
System.out.println(pack);
}
/*
获取当前运行时类所在的包
*/
@Test
public void test7(){
Class clazz = Person.class;
Annotation[] annotations = clazz.getAnnotations();
System.out.println(Arrays.toString(annotations));
}
}
package com.qiaoyx.java2;
import com.qiaoyx.java1.Person;
import org.junit.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* 调用运行时类指定的结构:属性,方法,构造器
*
* @author: qyx
* @date: 2022-08-18 7:01
* @desc:
*/
public class ReflactionTest {
@Test
public void testField() throws Exception {
Class clazz = Person.class;
//获取指定的属性:要求运行时类的属性声明为public
//通常不采用此方法
Field id = clazz.getField("id");
Person person = (Person) clazz.newInstance();
//设置当前属性的值
id.set(person, 1001);
//获取当前属性的值
int pId = (int) id.get(person);
System.out.println(pId);
}
/*
⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
如何操作运行时类中指定的属性
*/
@Test
public void testField1() throws Exception {
Class clazz = Person.class;
//创建运行时类对象
Person person = (Person) clazz.newInstance();
//获取运行时类中指定的变量名属性
Field name = clazz.getDeclaredField("name");
//保证当前属性是可访问的
name.setAccessible(true);
//获取,设置指定对象的此属性值
name.set(person, "Tom");
System.out.println(name.get(person));
}
/*
如何操作运行时类指定的方法 (需要掌握)
*/
@Test
public void testMethod() throws Exception {
Class clazz = Person.class;
//创建运行时类的对象
Person person = (Person) clazz.newInstance();
//1.获取指定的某个方法
/*
获取指定某个方法
getDeclaredMethod()
参数一:指明获取的方法名称 参数二:指明获取方法的形参列表
*/
Method show = clazz.getDeclaredMethod("show", String.class);
/*
invoke():参数一:方法的调用着 参数二:给方法形参赋值的实参
*/
//保证当前方法是可访问的
show.setAccessible(true);
//调用方法的invoke()属性, 返回值为调用方法的返回值
Object retrunValue = show.invoke(person, "CHN");
System.out.println(retrunValue);
System.out.println("*************如何调用静态方法************");
//private static void showDesc()
Method showDesc = clazz.getDeclaredMethod("showDesc");
showDesc.setAccessible(true);
//如果调用的运行时类中的方法没有返回值,则invoke方法返回null
Object returnValue = showDesc.invoke(Person.class);
// Object returnValue = showDesc.invoke(null);
System.out.println(returnValue);
}
/*
如何调用运行时类中的指定构造器
*/
@Test
public void testConstructor() throws Exception {
Class clazz = Person.class;
/*
获取指定的构造器
getDeclaredConstructor();参数:指明构造器的形参列表
*/
Constructor declaredConstructor = clazz.getDeclaredConstructor(String.class);
//保证此构造器是可访问的
declaredConstructor.setAccessible(true);
//创建运行时类的对象
Object person = declaredConstructor.newInstance("Tom");
System.out.println(person);
}
}
package com.qiaoyx.java1;
/**
* @author: qyx
* @date: 2022-08-17 10:06
* @desc:
*/
@MyAnnotation(value = "hi")
public class Person extends Creature<String> implements Comparable<String>,MyInterface{
private String name;
int age;
public int id;
@MyAnnotation(value = "abc")
private Person(String name){
this.name = name;
}
public Person(){
}
Person(String name,int age){
this.name = name;
this.age = age;
}
@Override
public void info() {
System.out.println("我是一个人");
}
@Override
public int compareTo(String o) {
return 0;
}
@MyAnnotation
private String show(String nation){
System.out.println("我的国籍是" + nation);
return nation;
}
public String display(String interests,int age) throws NullPointerException,ClassCastException{
return interests + age;
}
private static void showDesc(){
System.out.println("我是一个可爱的人");
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", id=" + id +
'}';
}
}
package com.qiaoyx.java1;
/**
* @author: qyx
* @date: 2022-08-17 10:08
* @desc:
*/
public interface MyInterface {
void info();
}
package com.qiaoyx.java1;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.ElementType.LOCAL_VARIABLE;
/**
* @author: qyx
* @date: 2022-08-17 10:19
* @desc:
*/
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value() default "hello";
}
package com.qiaoyx.java1;
import java.io.Serializable;
/**
* @author: qyx
* @date: 2022-08-17 10:02
* @desc:
*/
public class Creature<T> implements Serializable {
private char gender;
public double weight;
private void breath(){
System.out.println("生物呼吸");
}
public void eat(){
System.out.println("生物吃东西");
}
}
java的反射代码
最新推荐文章于 2024-08-04 11:07:52 发布