B站视频指路:尚硅谷Java入门视频教程(在线答疑+Java面试真题)_哔哩哔哩_bilibili
写在前面:马上秋招,打算从0开始再学一遍Java,开个知识点记录贴,就当做课堂笔记吧.
Java Reflection
·Reflection(反射)是被视为动态语言的关键,反射机制允许程序在执行期借助Reflection API取得任何类的内部信息,并能直接操作任意对象的内部属性及方法
·加载完类之后,在堆内存的方法区中就产生了一个Class类型的对象(一个类只有一个Class对象),这个对象就包含了完整的类的结构信息.我们可以通过这个对象看到类的结构.这个对象就像一面镜子,透过这个镜子看到类的结构,所以,我们形象的称之为:反射.
动态语言VS静态语言:
Java反射机制提供的功能
·在运行时判断任意一个对象所属的类
·在运行时构造任意一个类的对象
·在运行时判断任意一个类所具有的成员变量和方法
·在运行时获取泛型信息
·在运行时调用任意一个对象的成员变量和方法
·在运行时处理注解
·生成动态代理
反射相关的主要API
class和Class不一样
调用反射前后 对于Person类的操作
tips:通过反射 可以调用Person类的私有结构 比如私有的构造器、方法、属性
import org.junit.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectionTest {
//反射之前对Person的操作
@Test
public void test1(){
//1.创建Person类的对象
Person p1 = new Person("z",1);
//2.通过对象 调用其背部的属性和方法
p1.age=10;
System.out.println(p1.toString());
p1.show();
//在Person类外部 不可以通过Person类的对象调用其内部的私有结构
//
}
//反射之后对Person的操作
@Test
public void test2() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
//1.通过反射 创建Person类的对象
Class aClass = Person.class;
Constructor constructor = aClass.getConstructor(String.class, int.class);
Object z = constructor.newInstance("z", 1);
Person p = (Person)z;
System.out.println(p.toString());
//2.通过反射 调用对象指定的属性、方法
//调用属性
Field age = aClass.getDeclaredField("age");
age.set(p,20);
System.out.println(p.toString());
//调用方法
Method shows = aClass.getDeclaredMethod("show");
shows.invoke(p);
//通过反射 可以调用Person类的私有结构 比如私有的构造器、方法、属性
//调用私有的构造器
Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);
declaredConstructor.setAccessible(true);
Person p1 = (Person) declaredConstructor.newInstance("zhangke");
System.out.println(p1);
//调用私有的属性
Field name = aClass.getDeclaredField("name");
name.setAccessible(true);
name.set(p1,"haha");
System.out.println(p1);
//调用私有的方法
Method showNation = aClass.getDeclaredMethod("showNation", String.class);
showNation.setAccessible(true);
String china = (String)showNation.invoke(p1, "china");//相当于p1.showNation("china");
System.out.println(china);
}
}
疑问:①通过直接new的方式或反射的方式都可以调用公共的结构,开发中用哪个?
建议:直接new的方式
反射的特征:动态性 在编译的时候确定不了new哪个类的对象 就用反射的方式
②反射机制与面向对象中的封装性是否矛盾?如何看待两个技术
不矛盾 封装性解决的是 建议你怎么调用的问题 反射解决的是你能不能调用的问题
关于java.lang.Class的理解
1. 类的加载过程:
①程序在经过javac.exe命令以后 会生成一个或多个字节码文件(.class结尾)
②接着我们使用java.exe命令对某个字节码文件进行解释运行 相当于将某个字节码文件加载到内存中.此过程就称为类的加载,加载到内存中的类 我们就称为运行时类 此运行时类 就作为Class的一个实例
2.换句话说 Class的实例就对应着一个运行时类
3.加载到内存中的运行时类 会缓存一定的时间 在此时间内 我们可以通过不同的方式来获取此运行实例
获取Class的实例的方式 前三种需要掌握
import org.junit.Test;
public class ClassTest {
@Test
//获取Class的实例的方式 前三种需要掌握
public void test() throws ClassNotFoundException {
//方式一:调用运行时类的属性:.class
Class personClass = Person.class;
System.out.println(personClass);
//方式二:通过运行时类的对象 调用getClass()
Person p1 = new Person();
Class aClass = p1.getClass();
System.out.println(aClass);
//方式三:调用Class的静态方法:forName(String classPath) 用的最多 体现动态性
Class person = Class.forName("Person");
System.out.println(person);
System.out.println(personClass == person);//true
System.out.println(personClass == aClass);//true
//方式四:使用类的加载器 classLoader
ClassLoader classLoader = ReflectionTest.class.getClassLoader();
Class person1 = classLoader.loadClass("Person");
System.out.println(person1 == personClass);
}
}
哪些类型可以有Class对象?
①class:外部类、成员(成员内部类 静态内部类)、局部内部类、匿名内部类
②interface:接口
③[ ]:数组
④enum:枚举
⑤annotation:注解@interface
⑥primitive type:基本数据类型
⑦void
//Class实例可以是哪些结构:
true
简单了解 类的加载过程
下面这个小知识点需要掌握
·properties读取配置文件
import org.junit.Test;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class DASFSDF {
@Test
public void test() throws IOException {
Properties properties = new Properties();
//此时的文件默认在Module下
//读取配置文件的方式一:
// FileInputStream fileInputStream = new FileInputStream("jdbc.properties");
// properties.load(fileInputStream);
//读取配置文件的方式二:
//此时的文件默认在src下
ClassLoader classLoader = DASFSDF.class.getClassLoader();
InputStream is = classLoader.getResourceAsStream("zhangke.properties");
properties.load(is);
String user = properties.getProperty("user");
String password = properties.getProperty("password");
System.out.println(user);
System.out.println(password);
}
}
创建运行时类的对象:
通过反射去创建对应的运行时类的对象
//newInstance():调用的还是Person的构造器 内部调用了运行时类的空参的构造器 要想此方法 正常的创建运行时类的对象 要求: ①运行是类必须提供空参构造器 ②空参的构造器访问权限要满足要求 通常设置为public 在javabean中 要求提供一个public的空参构造器: ①便于通过反射 创建运行时类的虚 ②便于子类继承此运行类时 默认调用super()时 保证父类有此构造器import org.junit.Test; public class newInstanceTest { @Test public void test() throws InstantiationException, IllegalAccessException { Class<Person> clazz = Person.class; Person o =(Person) clazz.newInstance(); System.out.println(o); } }
体会反射的动态性:
直到运行之前 都不知道new的是哪个对象
import org.junit.Test;
import java.util.Random;
import java.sql.*;
public class newInstanceTest {
@Test
public void test() {
for (int i = 0; i < 10; i++) {
int num = new Random().nextInt(3);//0,1,2
String classPath="";
switch (num){
case 0:
classPath = "java.util.Date";
break;
case 1:
// classPath = "java.sql.Date";//他没有空参构造器 所以会
classPath = "java.lang.Object";
break;
case 2:
classPath = "Person";
break;
}
try {
Object instance = getInstance(classPath);
System.out.println(instance);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/*
创建一个指定类的对象
classPath:指定类的全类名
*/
public Object getInstance(String classPath) throws Exception {
Class aClass = Class.forName(classPath);
return aClass.newInstance();
}
}
反射获取运行时类的属性结构及其内部结构
//获取其属性结构
//getFields():获取当前运行时类及其父类中声明为public访问权限的属性
//getDeclaredFields():获取当前运行时类中声明的所有的属性(不包含父类中声明的属性)
package test2;
import hahah.Person;
import org.junit.Test;
import java.lang.reflect.Field;
/*
获取当前运行时类的属性结构
*/
public class FieldTest {
@Test
public void test(){
Class clazz = Person.class;
//获取其属性结构
//getFields():获取当前运行时类及其父类中声明为public访问权限的属性
Field[] fields = clazz.getFields();
for (Field obj:fields) {
System.out.println(obj);
}
System.out.println();
//getDeclaredFields():获取当前运行时类中声明的所有的属性(不包含父类中声明的属性)
Field[] declaredFields = clazz.getDeclaredFields();
for (Field obj:declaredFields) {
System.out.println(obj);
}
}
}
//获取某个属性结构的详细信息
@Test
//权限修饰符 数据类型 变量名
public void test2(){
Class clazz = Person.class;
//getDeclaredFields():获取当前运行时类中声明的所有的属性(不包含父类中声明的属性)
Field[] declaredFields = clazz.getDeclaredFields();
for (Field obj:declaredFields) {
//1.权限修饰符
int modifiers = obj.getModifiers();
System.out.print(Modifier.toString(modifiers)+"\t");
//2.数据类型
Class type = obj.getType();
System.out.print(type.getName() + "\t");
//变量名
System.out.println(obj.getName());
System.out.println();
}
}
获取其方法结构
@Test
public void test(){
Class clazz = Person.class;
//getMethods():获取当前运行时类及其所有父类所有声明为public的方法
Method[] methods = clazz.getMethods();
for (Method m:methods) {
System.out.println(m);
}
System.out.println("***************");
//getDeclaredMethods():获取当前运行时类中声明所有的方法 不包含父类方法
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method m:declaredMethods) {
System.out.println(m);
}
}
获取当前类运行对象声明方法的详细结构(了解即可 一般不会这么无聊)
获取注解 声明周期要够
package test2;
import hahah.Person;
import org.junit.Test;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/*
获取当前运行时类的方法结构
*/
public class FieldTest {
@Test
public void test(){
Class clazz = Person.class;
//getMethods():获取当前运行时类及其所有父类所有声明为public的方法
Method[] methods = clazz.getMethods();
for (Method m:methods) {
System.out.println(m);
}
System.out.println("***************");
//getDeclaredMethods():获取当前运行时类中声明所有的方法 不包含父类方法
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method m:declaredMethods) {
System.out.println(m);
}
}
@Test
//@Xxx
//权限修饰符 返回值类型 方法名(形参类型1 形参名1....) throws xxxException{}
public void test2(){
Class clazz = Person.class;
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method m:declaredMethods) {
//1.获取方法声明的注解
Annotation[] annotation = m.getAnnotations();
for (Annotation a: annotation) {
System.out.println(a);
}
//2.获取权限修饰符
System.out.print(Modifier.toString(m.getModifiers()) + "\t");
//3.返回值类型
System.out.print(m.getReturnType().getName()+"\t");
//4.方法名
System.out.print(m.getName());
System.out.print("(");
//5.形参列表
Class[] parameterTypes = m.getParameterTypes();
if(!(parameterTypes==null&¶meterTypes.length==0)){
for (int i= 0 ;i<parameterTypes.length;i++) {
if(i==parameterTypes.length-1){
System.out.print(parameterTypes[i].getName()+" args_"+i);
}else {
System.out.print(parameterTypes[i].getName()+" args_"+i+",");
}
}
}
System.out.print(") ");
//6.抛出的异常
Class[] exceptionTypes = m.getExceptionTypes();
if(exceptionTypes.length!=0){
System.out.print("throws"+" ");
for (int i = 0; i < exceptionTypes.length; i++) {
if(i==exceptionTypes.length-1){
System.out.print(exceptionTypes[i].getName());
}else{
System.out.print(exceptionTypes[i].getName() + ",");
}
}
}
System.out.println();
}
}
}
获取构造器结构
@Test
public void test(){
Class clazz = Person.class;
//getConstructors():获取当前运行时类中所有声明为public的构造器
Constructor[] constructors = clazz.getConstructors();
for (Constructor c:constructors) {
System.out.println(c);
}
System.out.println();
//getConstructors():获取当前运行时类中所有的构造器
Constructor[] declaredConstructors = clazz.getDeclaredConstructors();
for (Constructor c:declaredConstructors) {
System.out.println(c);
}
}
获取运行时类的父类
@Test
public void test2(){
Class clszz = Person.class;
Class superclass = clszz.getSuperclass();
System.out.println(superclass);
}
获取运行时类带泛型的父类
public void test2(){
Class clszz = Person.class;
Type genericSuperclass = clszz.getGenericSuperclass();
System.out.println(genericSuperclass);
}
获取运行时类带泛型的父类的泛型
public void test2(){
Class clszz = Person.class;
Type genericSuperclass = clszz.getGenericSuperclass();
ParameterizedType p = (ParameterizedType)genericSuperclass;
Type[] actualTypeArguments = p.getActualTypeArguments();
System.out.println(((Class)actualTypeArguments[0]).getName());
}
获取运行时类和其父类实现的接口
@Test
public void test(){
Class clazz = Person.class;
Class[] interfaces = clazz.getInterfaces();
for(Class s:interfaces){
System.out.println(s);
}
System.out.println();
Class[] interfaces1 = clazz.getSuperclass().getInterfaces();
for(Class s:interfaces1){
System.out.println(s);
}
}
获取运行时类所在的包
@Test
public void test(){
Class clazz = Person.class;
Package aPackage = clazz.getPackage();
System.out.println(aPackage);
}
获取运行时类声明的注解
@Test
public void test(){
Class clazz = Person.class;
Annotation[] annotations = clazz.getAnnotations();
for (Annotation a:annotations) {
System.out.println(a);
}
}
调用运行时类中指定的结构:属性(静态 非静态)、方法(静态 非静态)、构造器
1.属性--需要掌握
方式1:通常不用此方式 因为只能获取pulic的
@Test
public void test() throws Exception {
Class clazz = Person.class;
//创建运行时类的对象
Person p = (Person)clazz.getDeclaredConstructor().newInstance();
//获取指定的属性:运行时类的属性声明为public
Field id = clazz.getField("id");
//设置/获取当前属性的值
/*
set():参数一 指明设置哪个对象的属性 参数二:将此属性值设置为多少
get():参数一 获取哪个对象的当前属性值
*/
id.set(p,1);
int o = (int) id.get(p);
System.out.println(o);
}
方式2:注意setAccessible()
@Test
public void test2() throws Exception{
Class clazz = Person.class;
//创建运行时类的对象
Person p = (Person)clazz.getDeclaredConstructor().newInstance();
//getDeclaredField(String filedName):获取运行时类指定变量名的属性
Field name = clazz.getDeclaredField("name");
//保证当前属性是 可访问的
name.setAccessible(true);
//获取、设置指定对象的此属性值
name.set(p,"ba");
String n = (String) name.get(p);
System.out.println(n);
//静态属性
Field year = clazz.getDeclaredField("year");
year.setAccessible(true);
year.set(clazz,1234);
int o = (int)year.get(clazz);
System.out.println(o);
}
2.方法--需要掌握
package test2;
import hahah.Person;
import org.junit.Test;
import java.lang.reflect.Method;
public class FieldTest {
@Test
public void test2() throws Exception{
Class clazz = Person.class;
//创建运行时类的对象
Person p = (Person)clazz.getDeclaredConstructor().newInstance();
//非静态的方法
//获取指定的某方法
//getDeclaredMethod():参数1 指明获取的方法的名称 参数2 指明获取方法的形参列表
Method show = clazz.getDeclaredMethod("show",String.class);
//保证当前的方法是可访问的
show.setAccessible(true);
//invoke():参数1 方法的调用者 参数2 给方法的形参赋值
//invoke()的返回值 即为对应类中调用方法的返回值
String returnValue = (String) show.invoke(p, "kkk");//String s = p.show("kkk");
System.out.println(returnValue);
//静态的方法
Method showDesc = clazz.getDeclaredMethod("showDesc");
showDesc.setAccessible(true);
//若调用的运行时类 没有返回值 则此invoke()返回null
Object invoke = showDesc.invoke(Person.class);
System.out.println(invoke);
}
}
3.构造器--了解即可(常用的是clazz.newInstance())
@Test
public void test21() throws Exception{
Class clazz = Person.class;
//创建运行时类的对象
Person p = (Person)clazz.getDeclaredConstructor().newInstance();
//获取指定的构造器
//getDeclaredConstructor():参数 指明构造器的参数列表
Constructor constructor = clazz.getDeclaredConstructor(String.class);
//保证此构造器可访问
constructor.setAccessible(true);
//调用此构造器 创建此构造器运行时类的对象
Person qwe = (Person) constructor.newInstance("qwe");
System.out.println(qwe);
}
创建类的对象的方式
方式二: calendar、IntgetAddress
反射的应用--->动态代理:
·代理设计模式的原理:
使用一个代理将对象包装起来,然后用该代理对象取代原始对象.任何对原始对象的调用都要通过代理.代理对象决定是否以及何时将方法调用转到原始对象上
·之前的代理机制操作,属于静态代理,特征是代理类和目标对象的类都是在编译期间确定下来,不利于程序的扩展.同时,每一个代理类只能为一个借口服务,这样一来程序开发中必然产生过多的代理. 最好可以通过一个代理类完成全部的代理功能
·动态代理是指客户通过代理类来调用其它对象的方法,并且是在程序运行时根据需要动态创建目标类的代理对象
·动态代理使用场合:
①调试 ②远程方法调用
·动态代理相比于静态代理的优点
抽象角色中(接口)声明的所有方法都被转移到调用处理器一个集中的方法中处理,这样,我们可以更加灵活和统一的处理众多的方法
静态代理举例:
特点:代理类和被代理类在编译期间 就确定下来了
package daiLi;
interface ClothFactory{
void produceCloth();
}
//代理类
class ProxyProduceCloth implements ClothFactory{
private ClothFactory factory;//用被代理类对象进行实例化
public ProxyProduceCloth(ClothFactory factory){
this.factory=factory;
}
@Override
public void produceCloth() {
System.out.println("代理工厂做准备");
factory.produceCloth();;
System.out.println("代理工厂做收尾");
}
}
//被代理类
class NikeClothFactory implements ClothFactory{
@Override
public void produceCloth() {
System.out.println("Nike生产一批运动服");
}
}
public class jingtaidaili {
public static void main(String[] args) {
//创建被代理类的对象
NikeClothFactory nike = new NikeClothFactory();
//创建代理类的对象
ProxyProduceCloth proxyProduceCloth = new ProxyProduceCloth(nike);
//ClothFactory proxyProduceCloth = new ProxyProduceCloth(nike); 一样的
proxyProduceCloth.produceCloth();
}
}
动态代理举例:
要想实现动态代理 需要解决的问题
①如何根据加载到内存中的被代理类 动态的创建一个代理类及其对象
②当通过代理类的对象调用方法a时 如何动态的去调用被代理类中的同名方法a
package daiLi;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface human{
String getBelief();
void eat(String food);
}
//被代理类
class SuperMan implements human{
@Override
public String getBelief() {
return "i can play";
}
@Override
public void eat(String food) {
System.out.println("我喜欢吃"+food);
}
}
//代理类
class ProxyFactory{
//调用此方法 返回一个代理类的对象 解决问题1
public static Object getProxyInstance(Object obj){//obj:即被代理类的对象
MyInvocationHandler handler = new MyInvocationHandler();
handler.bind(obj);
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),handler);
}
}
class MyInvocationHandler implements InvocationHandler{
private Object obj;//需要使用被代理类的对象进行赋值
public void bind(Object obj){
this.obj=obj;
}
//当我们通过代理类的方法 调用方法a时 就会自动的调用如下的方法:invoke()
//将被代理类要执行的方法a的功能声明在invoke()中
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//method():即为代理类对象调用的方法 此方法也就作为了被代理类对象要调用的方法
//obj:被代理类的对象
Object returnValue = method.invoke(obj, args);
//上述方法的返回值就作为当前类中的invoke()的返回值
return returnValue;
}
}
public class dongtaidaili {
public static void main(String[] args) {
SuperMan superMan = new SuperMan();
//proxyInstance:代理类的对象
human proxyInstance = (human)ProxyFactory.getProxyInstance(superMan);//动态造代理类的对象
//当通过代理类对象调用方法时 会自动调用被代理类中的同名方法
System.out.println(proxyInstance.getBelief());//自动的调用invoke() getBelief()就是Method method
proxyInstance.eat("beef");//自动的调用invoke() eat()就是Method method
System.out.println("*****************************");
NikeClothFactory nikeClothFactory = new NikeClothFactory();
ClothFactory instance = (ClothFactory)ProxyFactory.getProxyInstance(nikeClothFactory);
instance.produceCloth();
}
}
动态代理与AOP
例:
package daiLi;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface human{
String getBelief();
void eat(String food);
}
//被代理类
class SuperMan implements human{
@Override
public String getBelief() {
return "i can play";
}
@Override
public void eat(String food) {
System.out.println("我喜欢吃"+food);
}
}
//代理类
class ProxyFactory{
//调用此方法 返回一个代理类的对象 解决问题1
public static Object getProxyInstance(Object obj){//obj:即被代理类的对象
MyInvocationHandler handler = new MyInvocationHandler();
handler.bind(obj);
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),handler);
}
}
class MyInvocationHandler implements InvocationHandler{
private Object obj;//需要使用被代理类的对象进行赋值
public void bind(Object obj){
this.obj=obj;
}
//当我们通过代理类的方法 调用方法a时 就会自动的调用如下的方法:invoke()
//将被代理类要执行的方法a的功能声明在invoke()中
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
hunamUtil util = new hunamUtil();
util.method1();
//method():即为代理类对象调用的方法 此方法也就作为了被代理类对象要调用的方法
//obj:被代理类的对象
Object returnValue = method.invoke(obj, args);
//上述方法的返回值就作为当前类中的invoke()的返回值
util.method2();
return returnValue;
}
}
class hunamUtil{
public void method1(){
System.out.println("___________________1__________________");
}
public void method2(){
System.out.println("___________________2__________________");
}
}
public class dongtaidaili {
public static void main(String[] args) {
SuperMan superMan = new SuperMan();
//proxyInstance:代理类的对象
human proxyInstance = (human)ProxyFactory.getProxyInstance(superMan);//动态造代理类的对象
//当通过代理类对象调用方法时 会自动调用被代理类中的同名方法
System.out.println(proxyInstance.getBelief());//自动的调用invoke() getBelief()就是Method method
proxyInstance.eat("beef");//自动的调用invoke() eat()就是Method method
System.out.println("*****************************");
NikeClothFactory nikeClothFactory = new NikeClothFactory();
ClothFactory instance = (ClothFactory)ProxyFactory.getProxyInstance(nikeClothFactory);
instance.produceCloth();
}
}