java 集合反射_Java 基础 -- 泛型、集合、IO、反射

这篇博客回顾了Java基础中的关键知识点,包括泛型的使用,如默认类型为Object、继承泛型类时的类型指定,以及泛型在DAO设计模式中的应用。此外,文章讨论了静态方法中不能使用泛型的原因,并介绍了集合Map的遍历方式。接着,作者通过示例展示了反射在获取方法、属性信息上的应用。同时,博客还涵盖了Comparator的使用来实现集合自定义排序,以及IO操作,如读取文件字节数和不同方式的文件复制,包括使用缓冲流提高效率。
摘要由CSDN通过智能技术生成

计划把 Java 基础的有些部分再次看一遍,巩固一下,下面以及以后就会分享自己再次学习的一点笔记!不是有关标题的所有知识点,只是自己觉得模糊的一些知识点。

1.  对于泛型类而言,你若没有指明其类型,默认为Object;

2.  在继承泛型类以及接口的时候可以指明泛型的类型,也可以不指明;

3.   泛型也数据库中的应用:

写一个 DAO 类对数据库中的数据进行增删改查其类型声明为 。每张表对应一个类,对应每一张表实现一个类继承该 DAO 类并指明 DAO 泛型为该数据表对应的类,再实现一个与该表匹配的 DAO 操作类,这样就不必在每一个数据表的操作实现类中去实现增删改查的基本方法。例如(实际应用中大概就是这思想,下面的举例并不完整):

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 //数据表对应的类

2 public classCustomer{3 private intid;4 privateString name;5 ...6 }7

8 //所有数据表的操作类都要实现的 DAO 基类

9 public class DAO{10 //增

11 public voidadd(T t) {12 …13 }14 }15

16 public T get(intindex) {17 //查

18 return null;19 }20

21 public voiddelete() {22 //删

23 …24 }25

26 public List getForList(intindex) {27 //查

28 return null;29 }30

31 //数据表操作对应的实现类

32 public class CustomerDao extends DAO{33

34 }35

36 //测试类

37 public classTest {38 public static voidmian(String[] args) {39 CustomerDao cus = newCustomerDao;40 Cus.add(newCustomer);41 }42 }

View Code

4.   静态方法中不可以使用泛型(static)

因为static 声明的方法或者类以及变量都是在类初始化的时候初始化,而泛型是在运行的时候才回去初始化的,所以就出现了问题(后出现的调用了先出现的)。

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

publicT t;//Error

public static voidshow() {

System.out.println(t);

}

View Code

5.  通配符

可以读取声明为通配符的集合,但不可往里写入元素(读的时候可以把元素都认为是 Object,但写的时候其声明为 ?,不是 Object,也就是说写什么类型都是错的,但可以存 null),例如

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

Public voidtestList() {

List strList = new ArrayList<>();

strList.add(“Hello”);

strList.add(“World”);//correct

List> list =strList;//error

list.add(“hi”);

list.add(123);//correct

list.add(null);

}

View Code

6.  集合Map 的遍历

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packagecom.java.map.test;importjava.util.ArrayList;importjava.util.Collection;importjava.util.Collections;importjava.util.HashMap;importjava.util.Iterator;importjava.util.List;importjava.util.Map;importjava.util.Set;public classMapEntry {public static voidmain(String[] args) {

Map map = new HashMap<>();

map.put(1, "a");

map.put(2, "b");

map.put(3, "c");

map.put(4, "d");

map.put(5, "e");//得到 map 所有键的集合

Set keys =map.keySet();for(Integer key : map.keySet()) {

System.out.println(map.get(key));

}//利用迭代器 遍历

Iterator> it =map.entrySet().iterator();while(it.hasNext()) {

Map.Entry entry =it.next();

System.out.println(entry.getKey()+ " -> " +entry.getValue());

}//第三种

for (Map.Entryentry : map.entrySet()) {

System.out.println(entry.getValue());

}//遍历所有的 value 值

Collection values =map.values();for(String val : values) {

System.out.println(val+ ">>-");

}

Iterator i =values.iterator();while(i.hasNext()) {

System.out.println(i.next()+ "-->");

}

List lists = new ArrayList<>();

lists.add("1");

lists.add("2");

lists.add("3");

lists.add("4");

Iterator it2 =lists.iterator();while(it2.hasNext()) {

System.out.println(it2.next());

}

Collections.reverse(lists);

Iterator it3 =lists.iterator();//Comparator comparator = new

while(it3.hasNext()) {

System.out.println(it3.next()+ "");

}

}

}

View Code

7.  利用反射获取方法名和属性名,利用反射还可以获取构造器等其他信息

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packagecom.java.reflct.test;//实体类

public classPerson {privateString id;privateString name;public intphone;public voidsetId(String id) {this.id =id;

}publicString getId() {returnid;

}public voidsetName(String name) {this.name =name;

}publicString getName() {returnname;

}public void setPhone(intphone) {this.phone =phone;

}public intgetPhone() {returnphone;

}private voidprint() {

System.out.println("your id is " + id + ", your name is " + name + ", your phone is " + phone + "!");

}

@OverridepublicString toString() {return "Person [id=" + id + ", name=" + name + ", phone=" + phone + "]";

}

}packagecom.java.reflct.test;//测试类

importjava.lang.reflect.Field;importjava.lang.reflect.InvocationTargetException;importjava.lang.reflect.Method;public classTestReflect {public static voidmain(String[] args) {try{//通过 Class.forName("全类名"); 获取 Class,还以利用 对象名.getClass() 类名.class(); 获取Class

Class cla = Class.forName("com.java.reflct.test.Person");

Class cla2= Person.class;//获取所有的 变量,返回数组,包括私有变量

Field[] fields =cla2.getDeclaredFields();//遍历变量数组

for(Field fie : fields) {

System.out.println(fie+"-..-");

}//获取所有的方法,返回数组,包括私有方法

Method[] methods =cla.getDeclaredMethods();for(Method met : methods) {

System.out.println(met);

}try{//获取单个私有属性

Field field = cla.getDeclaredField("id");//打破封装

field.setAccessible(true);

System.out.println(field+ "<<>>");

}catch(NoSuchFieldException e) {//TODO Auto-generated catch block

e.printStackTrace();

}catch(SecurityException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

Method method= null;try{//获取单个私有方法

method = cla.getDeclaredMethod("print");//打破封装

method.setAccessible(true);

System.out.println(method+ ">><

}catch(NoSuchMethodException e) {//TODO Auto-generated catch block

e.printStackTrace();

}catch(SecurityException e) {//TODO Auto-generated catch block

e.printStackTrace();

}try{//通过cla.newInstance(); 获取类的对象

Person person =(Person) cla.newInstance();

person.setId("1");

person.setName("yinyin");

person.setPhone(110);

System.out.println(person+ "__>>__");try{//执行 person 对象的中 method 所对应的方法

method.invoke(person);

}catch(IllegalArgumentException e) {//TODO Auto-generated catch block

e.printStackTrace();

}catch(InvocationTargetException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}catch(InstantiationException e1) {//TODO Auto-generated catch block

e1.printStackTrace();

}catch(IllegalAccessException e1) {//TODO Auto-generated catch block

e1.printStackTrace();

}

}catch(ClassNotFoundException e) {

System.out.println("There is no class " +e);

}

}

}

View Code

8.  Comparator  类的使用(利用  Comparator  实现集合的自定义排序)

注意区分 Collections (集合的处理类)和 Collection (集合基类)

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packagecom.java.collection.test;importjava.util.ArrayList;importjava.util.Collections;importjava.util.Comparator;importjava.util.Iterator;importjava.util.List;/** Collections 是 Collection 的操作类*/

public classCollectionComparator {public static voidmain(String[] args) {

Comparator com = new Comparator(){

@Overridepublic intcompare(Customer o1, Customer o2) {//将 id 的比较值放入参数中,使得 id 相等时有其他的处理方法

int i =o1.getId().compareTo(o2.getId());//当 Id 相等的时候比较名字的顺序

if (i == 0) {//给 return 添加一个 - 号可以实现 “从大到小”

returno1.getName().compareTo(o2.getName());

}//Id 不相等时返回其值

returni;

}

};

List lists = new ArrayList<>();

lists.add(new Customer("yinyin", "110", 1001));

lists.add(new Customer("zhao", "10086", 1002));

lists.add(new Customer("ls", "10010", 1001));;

Collections.sort(lists, com);//利用匿名类实现自定义排序

/*Collections.sort(lists, new Comparator(){

@Override

public int compare(Customer o1, Customer o2) {

// 将 id 的比较值放入参数中,避免 id 相等没有其值

int i = o1.getId().compareTo(o2.getId());

// 当 Id 相等的时候比较名字的顺序

if (i == 0) {

return o1.getName().compareTo(o2.getName());

}

return i;

}

});*/

//利用迭代器遍历集合

Iterator it =lists.iterator();while(it.hasNext()) {

System.out.println(it.next());

}

}

}

View Code

9.  IO

读取目标文本文件的字节数

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packagecom.java.io.file.test;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.IOException;importjava.io.InputStream;public classMyIoTest {public static voidmain(String[] args) {//在 IO 中出现的异常最好都使用 try-catch 包裹起来,不要 throw,因为这样可以保证流的关闭在任何时候都可以正常执行

InputStream fileStream = null;int count = 0;try{

fileStream= new FileInputStream(new File("hello.txt"));//读取文件的下一个字节

while (fileStream.read() != -1) {

count++;

}//打印目标文件的字节数

System.out.println(count);

}catch(FileNotFoundException e) {//TODO Auto-generated catch block

e.printStackTrace();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}finally{try{

fileStream.close();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

View Code

实现文件的复制(InputStream 、OutputStream 和 Reader 、Writer)。文本文件的操作使用 Reader Writer(字符流) 去实现,效率高。但是不可以去操作媒体文件;媒体文件使用 InputStream OutputStream 去实现,也可以对文本文件进行操作,但是没有字符流高效。

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packagecom.java.io.file.test;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;public classCopyFile {public static voidmain(String[] args) {//设置一次从目标文件中读取多少字节

byte[] buffer = new byte[1024];int len = 0;

File file= new File("C:/Users/lenovo/Desktop/123.wmv");

InputStream fileInput= null;

OutputStream fileOut= null;try{

fileInput= newFileInputStream(file);

fileOut= new FileOutputStream(new File("C:/Users/lenovo/Desktop/trave2.wmv"));//len 的作用是防止读取文件时最后一次其长度不够读取被置为零,read() 返回读入缓冲区的字节总数

while ((len = fileInput.read(buffer)) != -1) {

fileOut.write(buffer,0, len);

}

System.out.println("SUCC");

}catch(FileNotFoundException e) {//TODO Auto-generated catch block

e.printStackTrace();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}finally{try{

fileOut.close();

fileInput.close();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}//利用 Reader Writer 实现

packagecom.java.io.file.test;importjava.io.File;importjava.io.FileNotFoundException;importjava.io.FileReader;importjava.io.FileWriter;importjava.io.IOException;importjava.io.Reader;importjava.io.Writer;public classReaderWriter {public static voidmain(String[] args) {

File file= new File("hello.txt");int len = 0;

Reader fileReader= null;

Writer fileWriter= null;char[] ch = new char[125];try{

fileReader= newFileReader(file);

fileWriter= new FileWriter(new File("world.txt"));while((len = fileReader.read(ch)) != -1) {

fileWriter.write(ch,0, len);

}

}catch(FileNotFoundException e) {//TODO Auto-generated catch block

e.printStackTrace();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}finally{try{

fileWriter.close();

fileReader.close();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

View Code

10.  利用缓冲流实现文件的复制操作,效率更高

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packagecom.java.io.file.test;importjava.io.BufferedInputStream;importjava.io.BufferedOutputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;public classTestBufferedCopy {//使用缓冲流实现文件的复制

public static voidmain(String[] args) {int len = 0;byte[] buffer = new byte[2048];

File file= new File("C:/Users/lenovo/Desktop/123.rmvb");

InputStream inputFile= null;

OutputStream outputFile= null;

BufferedInputStream bufferedInput= null;

BufferedOutputStream bufferedOutput= null;try{

inputFile= newFileInputStream(file);

outputFile= new FileOutputStream("C:/Users/lenovo/Desktop/456.rmvb");

bufferedInput= newBufferedInputStream(inputFile);

bufferedOutput= newBufferedOutputStream(outputFile);while((len = bufferedInput.read(buffer)) != -1) {

bufferedOutput.write(buffer,0, len);

}

System.out.println("SUCC");

}catch(FileNotFoundException e) {//TODO Auto-generated catch block

e.printStackTrace();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}finally{try{//只需关闭复制文件用到的就可以,即最后两个

bufferedOutput.close();

bufferedInput.close();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

View Code

上面的代码总结啥的都是自己平常练习过程中的代码和心得,对于知识点讲解覆盖的并不全面,还望谅解。初来乍到不知道该如何去写!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值