Day25

2024-01-09 20:30:04

Day25

一,注解

1,java自带的注解

import java.util.ArrayList;

public class Test01 {
	/**
	 * 知识点:Java自带的注解(内置注解)
	 */
	
	//@Override 重写的注解
	@Override
	public String toString() {
		return super.toString();
	}
	
	//@Deprecated 方法弃用(过时)的注解
	@Deprecated
	public static void method01(){
	}
	
	//@SuppressWarnings 镇压警告的注解
	@SuppressWarnings("all")
	public static void method02(){
		
		ArrayList list = new ArrayList();
		
		list.add(100);
		list.add(123.123);
		list.add("用良心做教育");
	}
}

2,自定义注解

public class Test01 {
	/**
	 * 知识点:自定义注解
	 */
	
	@MyAnnotation
	String name;
	
	@MyAnnotation
	private static void method() {
		
	}
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//作用在方法和类上
@Target({ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)//作用在运行时
public @interface MyAnnotation {
}

public class Test01 {
	/**
	 * 知识点:自定义注解
	 */
	
	@MyAnnotation(name="aaa",age=18)
	String name;
	
	@MyAnnotation(name="bbb")
	private static void method() {
		
	}
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
	//配置一些属性
	String name();
	int age() default 0;
}
public class Test01 {
	/**
	 * 知识点:自定义注解
	 */
	
	@MyAnnotation(value="aaa")
	String name;
	
	@MyAnnotation("aaa")
	private static void method01() {
		
	}
	
	@MyAnnotation()
	private static void method02() {
	}
	
	@MyAnnotation
	private static void method03() {
	}
}

//value属性的特殊点
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
	
	String value() default "xxx";
}

public class Test01{
	/**
	 * 知识点:自定义注解
	 */
	
	@MyAnnotation(value="aaa")
	String name;
	
	@MyAnnotation("aaa")
	private static void method01() {
		
	}
	
	@MyAnnotation({"aaa","bbb"})
	private static void method02() {
	}
	
	@MyAnnotation(value = {"aaa","bbb"})
	private static void method03() {
	}
	
	@MyAnnotation()
	private static void method04() {
	}
	
	@MyAnnotation
	private static void method05() {
	}
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
	
	String[] value() default {"aaa","bbb"};
}

二,反射

1,初识反射

知识点:反射的概念

  •  获取类的class对象,操作class文件的技术
    
public class Test01 {
	/*
	 * 
	 * 知识点:获取类的class对象
	 */
	public static void main(String[] args) throws ClassNotFoundException {
		
		//获取class对象方式一:
		Class<? extends Student> clazz1 = Student.class;
		
		//获取class对象方式二:
		Student stu = new Student();
		Class<? extends Student> clazz2 = stu.getClass();
		
		//获取class对象方式三:--推荐
		Class<?> clazz3 = Class.forName("com.qf.reflex01.Student");
		
		System.out.println(clazz1 == clazz2);//true
		System.out.println(clazz1 == clazz3);//true
		
	}
}

import java.util.ArrayList;
import java.util.HashMap;
import java.util.TreeMap;
//自定义的注解
@MyAnnotation(name="杨彩虹",info="aaa")
public class Student<T> extends Person{

	@MyAnnotation(name="刘婷婷",info="bbb")
	private String classId;
	
	private String id;
	
	public static final String aaa = "用良心做教育";
	
	public ArrayList<Float> list;
	
	@MyAnnotation(name="朱雯瑄",info="ccc")
	public HashMap<String, Integer> method05(ArrayList<Double> list,TreeMap<String, Character> map){
		return null;
	}
	
	public Student() {
	}

	public Student(String name, char sex, int age, String classId, String id) {
		super(name, sex, age);
		this.classId = classId;
		this.id = id;
	}
	
	public Student(String name, Character sex, int age, String classId, String id) {
		super(name, sex, age);
		this.classId = classId;
		this.id = id;
	}
	
	public String getClassId() {
		return classId;
	}

	public void setClassId(@MyAnnotation(name="龙和娟",info="ddd")String classId) {
		this.classId = classId;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	@Override
	public String toString() {
		return "Student [classId=" + classId + ", id=" + id + ", getName()=" + getName() + ", getSex()=" + getSex()
				+ ", getAge()=" + getAge() + "]";
	}

	public void study(){
		super.eat();
		System.out.println(super.getName() + "写代码");
		super.sleep();
	}
	
	public void method01(String str,int a,int b){
		System.out.println(str + " -- " + a + " -- " + b);
	}
	
	public String method02(){
		return "用良心做教育";
	}
	
	public String method03(String str,int a,int b){
		return "用良心做教育 -- " + str + " -- " + a + " -- " + b;
	}
	
	private static final synchronized void method04(){
		System.out.println("静态方法");
	}
}

public class Person {
	
	private String name;
	private char sex;
	private int age;
	
	public String bbb;
	
	public Person() {
	}

	public Person(String name, char sex, int age) {
		this.name = name;
		this.sex = sex;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public char getSex() {
		return sex;
	}

	public void setSex(char sex) {
		this.sex = sex;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", sex=" + sex + ", age=" + age + "]";
	}
	
	public void eat(){
		System.out.println(this.name + "吃饭饭");
	}
	
	public void sleep(){
		System.out.println(this.name + "睡觉觉");
	}
}
import static java.lang.annotation.ElementType.*;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({TYPE,FIELD,METHOD,PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {

	String name();
	String info();
}

2,获取类的class对象

import java.io.IOException;
import java.util.Properties;

public class Test02 {
	/**
	 * 知识点:获取类的class对象
	 */
	public static void main(String[] args) throws ClassNotFoundException, IOException {
		
		Properties p = new Properties();
					p.load(Test02.class.getClassLoader().getResourceAsStream("ClassConfig.properties"));
		
		String path = p.getProperty("path");
		
		Class<?> clazz = Class.forName(path);
		System.out.println(clazz);
	}
}

3,利用反射操作属性

import java.io.IOException;
import com.qf.utils.ReflectUtil;

public class Test03 {
	/**
	 * 知识点:利用反射操作属性
	 */
	public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
		
//		Properties p = new Properties();
//		p.load(Test03.class.getClassLoader().getResourceAsStream("ClassConfig.properties"));
//		String path = p.getProperty("path");
//		Class<?> clazz = Class.forName(path);
		
		//获取本类及其父类公有的属性对象
//		Field[] fields = clazz.getFields();
//		for (Field field : fields) {
//			System.out.println(field);
//		}
		
		//获取本类所有的属性对象
//		Field[] fields = clazz.getDeclaredFields();
//		for (Field field : fields) {
//			System.out.println(field);
//		}
		
		//获取父类的class对象
//		Class<?> superclass = clazz.getSuperclass();
//		System.out.println(superclass);
		
		//获取本类及其父类所有的属性对象
//		for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
//			Field[] fields = c.getDeclaredFields();
//			for (Field field : fields) {
//				System.out.println(field);
//			}
//		}
		
		//获取本类指定的属性对象
//		Field field = clazz.getDeclaredField("aaa");
		//获取属性参数变量
//		int modifiers = field.getModifiers();
		//获取属性信息
//		System.out.println("判断是否使用public修饰:" + Modifier.isPublic(modifiers));
//		System.out.println("判断是否使用protected修饰:" + Modifier.isProtected(modifiers));
//		System.out.println("判断是否使用private修饰:" + Modifier.isPrivate(modifiers));
//		System.out.println("判断是否使用static修饰:" + Modifier.isStatic(modifiers));
//		System.out.println("判断是否使用final修饰:" + Modifier.isFinal(modifiers));
		
		//设置对象的属性
//		Student stu = new Student();
//		Field classIdField = clazz.getDeclaredField("classId");
//		classIdField.setAccessible(true);//设置修改权限
//		classIdField.set(stu, "2308");
		//获取对象的属性
//		Object value = classIdField.get(stu);
//		System.out.println(value);
		
		//设置对象的属性
		Student stu = new Student();
		ReflectUtil.setField(stu, "name", "杨彩虹");
		ReflectUtil.setField(stu, "sex", '女');
		ReflectUtil.setField(stu, "age", 18);
		ReflectUtil.setField(stu, "classId", "2308");
		ReflectUtil.setField(stu, "id", "001");
		
		//获取对象的属性
		String name = (String) ReflectUtil.getField(stu, "name");
		char sex = (char) ReflectUtil.getField(stu, "sex");
		int age = (int) ReflectUtil.getField(stu, "age");
		String classId = (String) ReflectUtil.getField(stu, "classId");
		String id = (String) ReflectUtil.getField(stu, "id");
		System.out.println(name + " -- " + sex + " -- " + age + " -- " + classId + " -- " + id);
	}
}

4,用反射操作构造方法


import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import com.qf.utils.ReflectUtil;

public class Test04 {
	
	/**
	 * 知识点:利用反射 操作构造方法
	 */
	public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
		
//		Properties p = new Properties();
//		p.load(Test04.class.getClassLoader().getResourceAsStream("ClassConfig.properties"));
//		String path = p.getProperty("path");
//		Class<?> clazz = Class.forName(path);
		
		//获取本类公有的构造方法对象
//		Constructor<?>[] constructors = clazz.getConstructors();
//		for (Constructor<?> constructor : constructors) {
//			System.out.println(constructor);
//		}
		
		//获取本类所有的构造方法对象
//		Constructor<?>[] constructors = clazz.getDeclaredConstructors();
//		for (Constructor<?> constructor : constructors) {
//			System.out.println(constructor);
//		}
		
		//利用无参构造方法创建对象
//		Student stu = (Student) clazz.newInstance();
//		System.out.println(stu);
		
		//获取无参构造方法对象
//		Constructor<?> constructor = clazz.getDeclaredConstructor();
		//利用无参构造方法创建对象
//		Student stu = (Student) constructor.newInstance();
//		System.out.println(stu);
		
		//String name, char sex, int age, String classId, String id
		
		//获取有参构造对象
//		Constructor<?> constructor = clazz.getDeclaredConstructor(String.class,char.class,int.class,String.class,String.class);
		//利用有参构造方法创建对象
//		Student stu = (Student) constructor.newInstance("杨彩虹",'女',18,"2308","001");
//		System.out.println(stu);
		
		//利用工具类创建对象 -- 底层调用对应的有参构造
//		Class<?>[] parameterTypes = {String.class,char.class,int.class,String.class,String.class};
//		Object[] parameters = {"杨彩虹",'女',18,"2308","001"};
//		Student stu = ReflectUtil.newInstance(Student.class,parameterTypes,parameters);
//		System.out.println(stu);
		
		//利用工具类创建对象 -- 底层调用无参构造
		Class<?>[] parameterTypes = null;
		Object[] parameters = null;
		Student stu = ReflectUtil.newInstance(Student.class,parameterTypes,parameters);
		System.out.println(stu);
	}

}

5,利用反射操作方法


import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import com.qf.utils.ReflectUtil;

public class Test05 {
	/**
	 * 知识点:利用反射 操作方法
	 */
	public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		
//		Properties p = new Properties();
//		p.load(Test05.class.getClassLoader().getResourceAsStream("ClassConfig.properties"));
//		String path = p.getProperty("path");
//		Class<?> clazz = Class.forName(path);
		
		//获取本类及其父类的公有方法对象
//		Method[] methods = clazz.getMethods();
//		for (Method method : methods) {
//			System.out.println(method);
//		}
		
		//获取本类所有的方法对象
//		Method[] methods = clazz.getDeclaredMethods();
//		for (Method method : methods) {
//			System.out.println(method);
//		}
		
		//获取本类及其父类所有的方法对象
//		for(Class<?> c = clazz;c != null;c=c.getSuperclass()){
//			Method[] methods = c.getDeclaredMethods();
//			for (Method method : methods) {
//				System.out.println(method);
//			}
//		}
		
		Class<?>[] parameterTypes = {String.class,char.class,int.class,String.class,String.class};
		Object[] parameters = {"杨彩虹",'女',18,"2308","001"};
		Student stu = ReflectUtil.newInstance(Student.class,parameterTypes,parameters);
		
		//无参数无返回值的成员方法
//		Method studyMethod = clazz.getDeclaredMethod("study");
//		studyMethod.invoke(stu);
		
		//带参数的成员方法
//		Method method01 = clazz.getDeclaredMethod("method01",String.class,int.class,int.class);
//		method01.invoke(stu, "abc",10,20);
		
		//带返回值的成员方法
//		Method method02 = clazz.getDeclaredMethod("method02");
//		Object method02ReturnValue = method02.invoke(stu);
//		System.out.println(method02ReturnValue);
		
		//带参数带返回值的成员方法
//		Method method03 = clazz.getDeclaredMethod("method03",String.class,int.class,int.class);
//		Object method03ReturnValue = method03.invoke(stu,"abc",10,20);
//		System.out.println(method03ReturnValue);
		
		//调用静态方法
//		Method method04 = clazz.getDeclaredMethod("method04");
//		method04.setAccessible(true);
//		method04.invoke(null);
		
		//获取方法信息变量
//		int modifiers = method04.getModifiers();
		//获取方法信息
//		System.out.println("判断是否使用public修饰:" + Modifier.isPublic(modifiers));
//		System.out.println("判断是否使用protected修饰:" + Modifier.isProtected(modifiers));
//		System.out.println("判断是否使用private修饰:" + Modifier.isPrivate(modifiers));
//		System.out.println("判断是否使用static修饰:" + Modifier.isStatic(modifiers));
//		System.out.println("判断是否使用final修饰:" + Modifier.isFinal(modifiers));
//		System.out.println("判断是否使用abstract修饰:" + Modifier.isAbstract(modifiers));
//		System.out.println("判断是否使用synchronized修饰:" + Modifier.isSynchronized(modifiers));
		
		//利用工具类调用方法
		ReflectUtil.invoke(Student.class, stu, "study", null, null);
		
		ReflectUtil.invoke(Student.class, stu, "method01", new Class<?>[]{String.class,int.class,int.class}, new Object[]{"用良心做教育",10,20});
		
		Object method02ReturnValue = ReflectUtil.invoke(Student.class, stu, "method02", null, null);
		System.out.println(method02ReturnValue);
		
		Object method03ReturnValue = ReflectUtil.invoke(Student.class, stu, "method03", new Class<?>[]{String.class,int.class,int.class}, new Object[]{"用良心做教育",10,20});
		System.out.println(method03ReturnValue);
		
		ReflectUtil.invoke(Student.class, null, "method04", null, null);
	}
}

6,利用反射操作方法的参数和返回值

import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
import java.util.Properties;

import com.qf.utils.ReflectUtil;

public class Test06 {
	/**
	 * 知识点:利用反射操作方法的参数和返回值
	 * @throws IOException 
	 * @throws ClassNotFoundException 
	 */
	public static void main(String[] args) throws IOException, ClassNotFoundException {
		//获取class对象
		Properties p = new Properties();
	p.load(Test06.class.getClassLoader().getResourceAsStream("ClassConfig.properties"));
		String path = p.getProperty("path");
		Class<?> clazz = Class.forName(path);
		
		Method method03 = ReflectUtil.getMethod(clazz, "method03", String.class,int.class,int.class);
	
		//获取方法上的参数对象
		Parameter[] parameters = method03.getParameters();
		for (Parameter parameter : parameters) {
			System.out.println("获取参数的class对象:" + parameter.getType());
			
			//注意:参数名不会编译到class文件,底层使用arg0、arg1、arg2去命名
			System.out.println("获取参数名:" + parameter.getName());
		}
		
		System.out.println("-----------------");
	
		//获取方法上的返回值类型
		Class<?> returnType = method03.getReturnType();
		System.out.println(returnType);
		
		Type genericReturnType = method03.getGenericReturnType();
		System.out.println(genericReturnType);
	}
}

7,利用反射操作泛型

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Properties;
import java.util.TreeMap;

import com.qf.utils.ReflectUtil;

public class Test07 {

	/**
	 * 知识点:利用反射操作 泛型
	 * 
	 * 注意:类上的泛型是获取不到的!!!
	 * 原因:因为创建该类对象时才会确定泛型类型
	 */
	public static void main(String[] args) throws IOException, ClassNotFoundException {
		
		Properties p = new Properties();
		p.load(Test07.class.getClassLoader().getResourceAsStream("ClassConfig.properties"));
		String path = p.getProperty("path");
		Class<?> clazz = Class.forName(path);
		
		//获取属性的泛型类型
//		Field field = ReflectUtil.queryField(clazz, "list");
//		Type fieldType = field.getGenericType();//获取属性类型
//		ParameterizedType pt = (ParameterizedType) fieldType;
//		Type[] actualTypeArguments = pt.getActualTypeArguments();//获取属性上泛型的类型数组
//		for (Type type : actualTypeArguments) {
//			System.out.println(type);
//		}
		
		//获取方法上参数的泛型类型
//		Method method05 = ReflectUtil.getMethod(clazz, "method05", ArrayList.class,TreeMap.class);
//		Type[] genericParameterTypes = method05.getGenericParameterTypes();//获取参数类型数组
//		for (Type type : genericParameterTypes) {//遍历参数类型
//			ParameterizedType pt = (ParameterizedType) type;
//			Type[] actualTypeArguments = pt.getActualTypeArguments();//获取当前参数上的泛型数组
//			System.out.println(Arrays.toString(actualTypeArguments));
//		}
		
		//获取方法上返回值的泛型类型
		Method method05 = ReflectUtil.getMethod(clazz, "method05", ArrayList.class,TreeMap.class);
		Type genericReturnType = method05.getGenericReturnType();//获取返回值类型
		ParameterizedType pt = (ParameterizedType) genericReturnType;
		Type[] actualTypeArguments = pt.getActualTypeArguments();//获取返回值类型上的泛型数组
		System.out.println(Arrays.toString(actualTypeArguments));
	
	}
}

8,利用反射获取注解信息

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Properties;
import java.util.TreeMap;

import com.qf.utils.ReflectUtil;

public class Test08 {
	/**
	 * 知识点:利用反射获取注解信息
	 */
	public static void main(String[] args) throws IOException, ClassNotFoundException {
		
		Properties p = new Properties();
		p.load(Test06.class.getClassLoader().getResourceAsStream("ClassConfig.properties"));
		String path = p.getProperty("path");
		Class<?> clazz = Class.forName(path);
		
		//获取类上的注解信息
		MyAnnotation annotation1 = clazz.getDeclaredAnnotation(MyAnnotation.class);
		String name1 = annotation1.name();
		String info1 = annotation1.info();
		System.out.println(name1 + " -- " + info1);
		
		//获取属性上的注解信息
		Field field = ReflectUtil.queryField(clazz, "classId");
		field.setAccessible(true);
		MyAnnotation annotation2 = field.getAnnotation(MyAnnotation.class);
		String name2 = annotation2.name();
		String info2 = annotation2.info();
		System.out.println(name2 + " -- " + info2);
		
		//获取方法上的注解信息
		Method method05 = ReflectUtil.getMethod(clazz, "method05", ArrayList.class,TreeMap.class);
		MyAnnotation annotation3 = method05.getAnnotation(MyAnnotation.class);
		String name3 = annotation3.name();
		String info3 = annotation3.info();
		System.out.println(name3 + " -- " + info3);
	
		//获取参数上的注解信息
		Method setClassIdMethod = ReflectUtil.getMethod(clazz, "setClassId", String.class);
		Parameter[] parameters = setClassIdMethod.getParameters();
		for (Parameter parameter : parameters) {
			MyAnnotation annotation4 = parameter.getAnnotation(MyAnnotation.class);
			String name4 = annotation4.name();
			String info4 = annotation4.info();
			System.out.println(name4 + " -- " + info4);
		}
	}
}

9,利用反射操作数组

import java.lang.reflect.Array;

public class Test09 {
	/**
	 * 知识点:利用反射 操作数组
	 * 
	 * Array是 数组反射类
	 */
	public static void main(String[] args) {
		
		int[] arr = (int[]) Array.newInstance(int.class, 10);
		
		System.out.println("获取数组的长度:" + Array.getLength(arr));
		
		//遍历数组 - 设置元素
		for(int i = 0;i<Array.getLength(arr);i++){
			Array.set(arr, i, i+1);
		}
		
		//遍历数组 - 获取元素
		for(int i = 0;i<Array.getLength(arr);i++){
			int element = (int) Array.get(arr, i);
			System.out.println(element);
		}
	}
}
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//工具类
public class ReflectUtil {

	/**
	 * 查询本类及其父类的属性对象
	 * @param clazz class对象
	 * @param name 属性名
	 * @return 属性对象,如果没有就返回null
	 */
	public static Field queryField(Class<?> clazz,String name){
		
		for(Class<?> c = clazz;c!=null;c=c.getSuperclass()){
			try {
				Field field = c.getDeclaredField(name);
				return field;
			} catch (NoSuchFieldException e) {
			} catch (SecurityException e) {
			}
		}
		return null;
	}
	
	/**
	 * 设置属性值
	 * @param obj 对象
	 * @param name 属性名
	 * @param value 属性值
	 */
	public static void setField(Object obj,String name,Object value){
		Class<? extends Object> clazz = obj.getClass();
		Field field = queryField(clazz,name);
		if(field == null){
			return;
		}
		field.setAccessible(true);
		try {
			field.set(obj, value);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取属性
	 * @param obj 对象
	 * @param name 属性名
	 * @return 属性值
	 */
	public static Object getField(Object obj,String name){
		Class<? extends Object> clazz = obj.getClass();
		Field field = queryField(clazz,name);
		if(field == null){
			return null;
		}
		field.setAccessible(true);
		Object value = null;
		try {
			value = field.get(obj);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return value;
	}
	
	/**
	 * 创建对象
	 * @param clazz class对象
	 * @param parameterTypes 构造方法的参数类型数组
	 * @param parameters 构造方法的参数数组
	 * @return 对象
	 */
	@SuppressWarnings("unchecked")
	public static <T> T newInstance(Class<T> clazz,Class<?>[] parameterTypes,Object[] parameters){
		
		try {
			Constructor<?> constructor = clazz.getDeclaredConstructor(parameterTypes);
			constructor.setAccessible(true);
			Object obj = constructor.newInstance(parameters);
			return (T) obj;
		} catch (NoSuchMethodException | SecurityException | InstantiationException |  IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			return null;
		} 
	}
	
	/**
	 * 获取本类及其父类指定的方法
	 * @param clazz class对象
	 * @param name 方法名
	 * @param parameterTypes 方法参数的类型
	 * @return 方法对象
	 */
	public static Method getMethod(Class<?> clazz,String name,Class<?>... parameterTypes){
		for(Class<?> c = clazz;c!=null;c=c.getSuperclass()){
			try {
				Method method = c.getDeclaredMethod(name, parameterTypes);
				return method;
			} catch (NoSuchMethodException | SecurityException e) {
			}
		}
		return null;
	}
	
	/**
	 * 调用方法
	 * @param clazz class对象
	 * @param obj 对象
	 * @param name 方法名
	 * @param parameterTypes 参数类型数组
	 * @param parameters 参数数组
	 * @return 返回值
	 */
	public static Object invoke(Class<?> clazz,Object obj,String name,Class<?>[] parameterTypes,Object[] parameters){
		
		Method method = getMethod(clazz, name, parameterTypes);
		if(method == null){
			return null;
		}
		
		method.setAccessible(true);
		try {
			Object invoke = method.invoke(obj, parameters);
			return invoke;
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}

文章来源:https://blog.csdn.net/haikeydnk/article/details/135488375
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。