IO流 泛型 反射

6)对象流:


1)要使实体类实现序列化接口Serializable

public class Book implements Serializable


2)写入数据时,需要根据情况决定是否添加头部信息(Header),如果文件的length==0,说明是写入第一个对象,调用ObjectOutPutStream,写入头信息,如果length不是0
就使用自己的定义ObjectOutPutStream的子类,该类重写writerStreanHeader方法,返回空,用子类写后面的对象


public class MyObjectOutPutStream extends ObjectOutputStream {
public MyObjectOutPutStream(OutputStream out) throws IOException {
super(out);
}

@Override
protected void writeStreamHeader() throws IOException {
return;
}
}

 

3)读的时候,需要人为捕获EOFException

package com.iss.demo03.Util;

import com.iss.demo03.entity.Book;
import com.iss.demo03.model.MyObjectOutPutStream;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ObjectIOUtil {
public static File path,file;
public static void creatFile(){
path=new File("filees");
if(!path.exists()){
path.mkdirs();
}
file=new File(path,"book.txt");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void writeObject(Book book){
creatFile();
ObjectOutputStream oos;
FileOutputStream fos=null;
try {
new FileOutputStream(file,true);
if(file.length()==0){
oos=new ObjectOutputStream(fos);
}else{

oos=new MyObjectOutPutStream(fos);}

oos=new MyObjectOutPutStream(new FileOutputStream(file,true));
oos.writeObject(book);
oos.reset();//重置
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static List<Book> readObject(){
creatFile();
List<Book> books=new ArrayList<>();
try {
Book t;
ObjectInputStream ooi=new ObjectInputStream(new FileInputStream(file));
while ((t=(Book)ooi.readObject())!=null){
books.add(t);
}
ooi.close();

} catch (IOException e) {
// e.printStackTrace(); EOFException
System.out.println("文件已经读到末尾");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return books;
}
}
 


7)过渡流:把字节流转成字符流

   public static void main(String[] args) {
try {//字节流转化为字符流加到缓冲流
InputStreamReader ir=new InputStreamReader(new FileInputStream("files/time.txt"));
BufferedReader br=new BufferedReader(ir);
String t;
while ((t=br.readLine())!=null){
System.out.println(t+"\n");
}
ir.close();
br.close();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}


6.泛型和反射

1)泛型<>有多种数据类型
List<String> list = new ArrayList();
List<Book> list = new LinkedList();
Map<String,Object> map = new HashMap();

public class Student <T1,T2>{
private String name;
private T1 age;
private T2 score;
//        Student<Integer,Integer> stu=new Student<>("zhang",15,2);
// Student<String,Double> stu1=new Student<>("s","ss",2.0);
//


泛型的继承,类继承类,也可以实现泛型接口,泛型不能出现在静态方法里,可出现在参数里

public class Math<T1,T2,T3,T> extends Student<T1,T2> implements Favorite<T> {
private T f;
private T3 mathScore;

public Math(String name, T1 age, T2 score, T3 mathScore,T f) {
super(name, age, score);
this.mathScore = mathScore;
this.f=f;
}

@Override
public T getFavorite() {
return f;
}
public interface Favorite<T> {
T getFavorite();
}



Math<Integer,Integer,String,String> math=new Math<>("s",1,2,"s","jisuan");
math.getF();
//交换
public class Swapper <T>{
public T[]swap(T[]a){
T t;
t=a[0];
a[0]=a[1];
a[1]=t;
return a;
}
}
//       Swapper<Integer> swapper=new Swapper<>();
// Integer[]a1=new Integer[]{1,2};
// swapper.swap(a1);
// Swapper<Character>swapper1=new Swapper<>();
// Character[]a2=new Character[]{'a','b'};
// swapper1.swap(a2);
// System.out.println(a1[0]+","+a1[1]);
// System.out.println(a2[0]+","+a2[1]);

 


泛型的通配符

public static void getStudentInfo(Stu<?> stu){
System.out.println(stu);
}
Stu<String> stu3=new Stu("s","w","m");
Controller.getStudentInfo(stu3);

 

泛型的上限和下限
上限:<? extends Number> 可以是Number也可以是Number子类
下限:<? super Number> 可以是Number,也可以是Number的父类

public static void textshangxian(Stu<?extends Number>stu){
System.out.println("s"+stu);
}
Stu<Integer>stu=new Stu<>("wang",2,3);
Controller.textshangxian(stu);


2)反射(reflection): a)能够帮助java实现动态语言的机制.程序可以访问,检测和修改它自身状态或行为的一种能力,并能根据自身的行为的状态和结果,调整和修改应用所描述的行为的状态和相关的语义

b)反射的目的:创建更加灵活的代码,这些代码可以在运行时进行装配,在编译时不实例化对象,运行时
c)能完成的工作:
1)在运行时判断任意一个类的对象

2)在运行的时候构造任意一个类的对象

   try {
Class<?>clazz1=Class.forName("com.iss.demo06.entity.Student");
System.out.println(clazz1);
// Class<?>clazz2=new Student().getClass();
// Class<?>clazz3=Student.class;
// System.out.println(clazz3);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

Scanner sc=new Scanner(System.in);
Class<?>clazz = null;
clazz=Class.forName("com.iss.demo06.entity."+sc.next());

 

3)在运行时,获取任意一个对象的所具有的属性和方法

//        //获取属性
// Field[]fields= clazz.getDeclaredFields();//自己本类 getField自己和父类非私有的
// for (Field field:fields){
// // System.out.println(field);
// System.out.print("\t访问权限"+ Modifier.toString(field.getModifiers()));把整数转化为单词
// System.out.print("\t数据类型"+field.getType());
// System.out.print("\t属性名称"+field.getName());
// System.out.println();
// }
//        //获取方法
// Method[]m=clazz.getDeclaredMethods();//getMethods父类和自己
// for (Method method:m){
// System.out.print("\t访问权限"+Modifier.toString(method.getModifiers()));
// System.out.print("\t返回值类型"+method.getReturnType());
// System.out.print("\t方法名"+method.getName());
// System.out.print("\t参数:(");
// Class<?>[]types= method.getParameterTypes();//getParameterTypes参数类型 Class<?>[]
// for (int i=0;i<types.length;i++){
// System.out.print("第"+(i+1)+"类型"+types[i]);
// }
// System.out.print(")");
// System.out.println();
// }
//        //获取父类信息
// Class<?>clazzP=clazz.getSuperclass();
// System.out.println(clazzP);
// Field[] fields1=clazzP.getDeclaredFields();//属性
// for (Field field:fields1){
// System.out.println(field);
// }

 

4)在运行时,能调用任意一个对象的非私有的属性和方法

//动态生成那个对象
System.out.println("请输入是否创建那个对象的类");
Scanner sc=new Scanner(System.in);
Class<?>clazz = null;
try {
clazz=Class.forName("com.iss.demo06.entity."+sc.next());
Object object=clazz.newInstance();//newInstance变成一个对象
//通过反射实例化对象
Method[]m=clazz.getDeclaredMethods();//getMethods父类和自己
for (Method method:m){
String methodName=method.getName();
if(methodName.startsWith("set")){//set方法
String title=methodName.substring(3);//第三个元素开始取
String type=method.getParameterTypes()[0].toString();//参数类型get set一个属性有一对
System.out.println("请为"+title+"的属性输入数据,类型为:"+type);
if(type.indexOf("int")!=-1||type.indexOf("Integer")!=-1){//包含 -1没找到
method.invoke(object,sc.nextInt());//通过反射invoke调用set方法
//invoke 调用那个对象 object为那个对象赋值
}else {
method.invoke(object,sc.next());
}
}
}
//调用tostring方法
Method method=clazz.getMethod("toString");
String str=(String) method.invoke(object);
System.out.println(str);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}

 

d)反射要用到的类reflect包
Class: finall类不能被继承   forname    newInstance 
Constructor:构造方法
Field:成员变量 属性
Method:成员方法
Modifier:访问权限修饰符

//计算两地之间的时间,有三种交通工具,飞机,火车,汽车,距离用户交通都控制台输入,得到花费时间
public class demo01 {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("输入两地距离");
int distance=scanner.nextInt();
System.out.println("选择工具");
try {
Class<?> clazz=Class.forName("com.iss.demo06.demo01."+scanner.next());
Object object=clazz.newInstance();
Method method=clazz.getMethod("getSpeed");
Integer speed= (Integer)method.invoke(object);//如果有参数 例如(object,new Object[]{90,99})
System.out.println(1.0*distance/speed);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
public interface Common {
Integer getSpeed();
}


public class Car implements Common {
@Override
public Integer getSpeed() {
return 500;
}
}

public class Plane implements Common {
@Override
public Integer getSpeed() {
return 1000;
}
}

public class Train implements Common {
@Override
public Integer getSpeed() {
return 300;
}
}
posted @ 2021-03-12 11:14  YangYuJia  阅读(81)  评论(0)    收藏  举报