1:匿名内部类特点
匿名内部类具有一系列的限制,原因待会解释:
1、不能具有static成员域和成员函数和类。
2、不能具有static final 修饰的引用类型。
3、不能有自定义的构造函数。
4、不能具有静态代码块。
5、匿名内部类不能有类修饰符
只需要实例化一次,并且想使代码看起来精简时;
在Java的窗口程序设计中,用来编写“事件”的程序代码
private static void AnonymousInnerClass() {
DemoInterface demoInterface = new DemoInterface() {
@Override
public void Ear() {
System.out.println("测试");
}
};
demoInterface.Ear(); //调用方法
}
jdk动态代理里面就涉及到匿名内部类
package com.hp.demo01.fanshe;
import com.hp.demo01.DemoImp;
import com.hp.demo01.DemoInterface;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author SX
* @date 2020/8/23 15:42
*/
public class DemoProxy {
public static void main(String[] args) {
DemoImp demoImp = new DemoImp();
DemoInterface proxyInstance = (DemoInterface) Proxy.newProxyInstance(demoImp.getClass().getClassLoader(),
//类加载器材
demoImp.getClass().getInterfaces(),
//接口 -----匿名内部类
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object returnvalue = null;
System.out.println("我在你之前执行");
if ("Ea1".equals(method.getName())) {
method.invoke(demoImp, args);
}
System.out.println("我在你之后执行");
return returnvalue;
}
});
proxyInstance.Ear();
}
}
基于反射
2:反射一个方法demo
package com.hp.demo01.fanshe;
import com.hp.demo01.Student;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author SX
* @date 2020/8/23 16:20
*/
public class Fanshe1 {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class cstudent = Class.forName("com.hp.demo01.Student");
Student student= (Student) cstudent.newInstance();
Method eat = cstudent.getMethod("eat", String.class);
eat.setAccessible(true);
eat.invoke(student,"鱼");
}
}
3:IO的使用
private static void IO() throws IOException {
FileInputStream fis = new FileInputStream("C:\\Users\\Lenovo\\Desktop\\GSlogo.jpg");
FileOutputStream fos = new FileOutputStream("C:\\Users\\Lenovo\\Desktop\\ces\\GSlogo.jpg");
byte[] bytes = new byte[1024];
int len = 0;
while ((len = fis.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
fis.close();
fos.close();
}