反射,枚举

本文主要介绍了Java中的相关知识。IO部分涵盖字节数组流、数据流和对象流的输入输出及拷贝操作;反射机制能在运行时获取类的属性、方法等信息,还介绍了获取对象、构造器等的方法;枚举类隐式继承java.lang.enum抽象类,成员默认是public static final。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

1. io

1.1 字节数组流

1.1.1 输入流

1.1.2 输出流

1.1.3 拷贝

1.2 数据流

1.2.1 输入流

1.2.2 输出流

1.2.3 拷贝

1.3 对象流

1.3.1 序列化输出流

1.3.2 反序列化输入流

2. 反射(reflection)

2.1 获取对象

2.2 获取构造器

2.3 获取属性(字段)

2.4 获取方法

2.5 创建类型对象根据Class对象

2.6 获取父类(父接口)的Class对象

2.7 获取修饰符

3. 枚举类


  • 1. io

 * 节点流:
 *         字节数组流
 *             输入流:ByteArrayInputStream   
 *                没有新增方法---使用和InputStream一样
 *            输出流:ByteArrayOutputStream
 *                有有新增方法---不能够多态使用
 *                    byte[] toByteArray()   字节数组流转为字节数组

  • 1.1 字节数组流

  • 1.1.1 输入流

ByteArrayInputStream

无新增方法,可以多态使用

package day16.io;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ByteArrayInputStreamDemo01 {
	public static void main(String[] args) throws IOException {
		read("我叫刘文旭..".getBytes());
		//write();
	}
	
	//读
	public static void read(byte[] b) throws IOException{
		//创建流
		InputStream in = new ByteArrayInputStream(b);
		//操作
		byte []by=new byte[1024];
		int len = 0;
		String s = null;
		while((len=in.read(by))!=-1){
			s=new String(by,0,len);
		}
		System.out.println(s);
	}
	
	//写
	public static void write() throws IOException{
		//定义目的地
		byte[] dest;
		String s = "留我在原地,一脸疑问,一脸懵逼...";
		//定义流
		ByteArrayOutputStream by = new ByteArrayOutputStream();
		by.write(s.getBytes());
		dest = by.toByteArray();
		by.flush();
		by.close();
		System.out.println(new String(dest));
	}
}
  • 1.1.2 输出流

ByteArrayOutputStream

有新增方法,不可多态使用,toByteArray()

  • 1.1.3 拷贝

文件-----程序-----字节数组

字节数组---程序----文件

package day16.io;

import java.io.*;

public class ByteArrayInputStreamDemo02 {
	public static void main(String[] args) throws IOException {
		System.out.println(new String(toByteArray("D:/haha.txt")));
		read(toByteArray("D:/haha.txt"), "D:/haha1.txt");
	}
	
	//文件-----程序-----字节数组
	public static byte[] toByteArray(String src) throws IOException {
		//创建联系
		File f = new File(src);
		byte[] dest;
		//选择流
		InputStream in = new BufferedInputStream(new FileInputStream(f));
		ByteArrayOutputStream out =new ByteArrayOutputStream();
		
		byte[] car = new byte[1024];
		int len  = 0;
		while((len=in.read(car))!=-1){
			out.write(car,0,len);
		}
		dest = out.toByteArray();
		//关闭
		out.flush();
		in.close();
		return dest;
		
	}
	
	//字节数组--程序---文件
	public static void read(byte[]b,String dest) throws IOException{
		//创建流
		InputStream is = new BufferedInputStream(new ByteArrayInputStream(b));
		OutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
		byte[] car = new byte[1024];
		int len = 0;
		while((len=is.read(car))!=-1){
			out.write(car,0,len);
		}
		//强制刷出
		out.flush();
		//关闭
		is.close();
	}
}
  • 1.2 数据流

 * 处理流:
 *         基本数据类型流---数据类型+数据
 *             输入流:DataInputStream --readXXX()
 *             输出流:DataOutputStream --writeXXX()
 *         有新增方法,无法多态;
 *         写出的写出的顺序要与读入的顺序一致
 * 
 *         EOFException 文件存在,但是内容没有读到
 *        只能够读取到写出的源文件中,否则就算输内容相同的其他文件会跑异常

  • 1.2.1 输入流

package day16.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataInputStreamDemo03 {
	public static void main(String[] args) throws IOException {
		write("D:/haha.txt");
		read("D:/haha.txt");
	}
	
	//写出 --DataOutputStream
	public static void write(String dest) throws IOException {
		//创建流
		DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dest)));
		//创建数据
		int i =5;
		char ch = 'a';
		String s = "哈哈";
		boolean b = true;
		out.writeInt(i);
		out.writeChar(ch);
		out.writeUTF(s);
		out.writeBoolean(b);
		//强制刷出
		out.flush();
		System.out.println("写出成功..");
		out.close();
	}
	
	//读入 --DataInputStream
	public static void read(String src) throws IOException {
		DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(src)));
		byte[]	bt = new byte[1024];
		 int i = in.readInt();
		 char ch = in.readChar();
		 String s = in.readUTF();
		 boolean b = in.readBoolean();
		 System.out.println("读入成功..");
		 in.close();
		 System.out.println(i+"\n"+ch+"\n"+s+"\n"+b);
		 
	}
}
  • 1.2.2 输出流

  • 1.2.3 拷贝

从文件中读到程序--写出到字节数组

package day16.io;

import java.io.*;

public class DataInputStreamDemo04 {
	public static void main(String[] args) throws IOException {
		writeFile("d:/haha2.txt");
		
		System.out.println(new String(readByteArray("d:/haha2.txt")));
	}

	/*
	 * 1.写出到文件
	 */
	public static void writeFile(String dest) throws IOException {
		// 1.源数据
		int i = 5;
		long l = 333;
		String s = "哈哈";
		boolean b = true;
		// 2.创建流
		DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(new File(dest))));
		out.writeInt(i);
		out.writeLong(l);
		out.writeUTF(s);
		out.writeBoolean(b);
		//3.强制刷出
		out.flush();
		//4.关闭
		out.close();
	}
	
	/*
	 * 从字节数组中读入到程序
	 */
	public static void read(byte[] src) throws IOException {
		DataInputStream in = new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(src)));
		 int i = in.readInt();
		 char ch = in.readChar();
		 String s = in.readUTF();
		 boolean b = in.readBoolean();
		 System.out.println("读入成功..");
		 in.close();
		 System.out.println(i+"\n"+ch+"\n"+s+"\n"+b);
		 
	}
	
	/*
	 * 2.从文件中读到程序--从程序写到字节数组
	 */
	public static byte[] readByteArray(String src) throws IOException {
		//创建流
		DataInputStream in=new DataInputStream(new BufferedInputStream(new FileInputStream(new File(src))));
		ByteArrayOutputStream by=new ByteArrayOutputStream();
		DataOutputStream out=new DataOutputStream(new BufferedOutputStream(by));
		
		//目的地
		byte[] dest;
		out.writeInt(in.readInt());
		out.writeLong(in.readLong());
		out.writeUTF(in.readUTF());
		out.writeBoolean(in.readBoolean());
		out.flush();
		System.out.println("写出成功..");
		dest = by.toByteArray();
		System.out.println("写到字节数组..");
		in.close();
		return dest;
	
	}
}
  • 1.3 对象流

 * 对象流:引用数据类型流 -- 数据类型+数据
 *         序列化输出流: ObjectOutputStream --- writeObject()
 *         反序列化输入流: ObjectInputStream ---  readObject()
 * 
 * 注意:
 *         先序列化后反序列化        反序列化的顺序要和序列化相同
 *         不是所有的类都能序列化    NotSerializableException    实现Serializable接口才可以序列化
 *      不是所有的属性都需要序列化  transient默认值

  • 1.3.1 序列化输出流

package day16.io;

import java.io.*;
import java.util.Arrays;

public class ObjectDemo05 {
	public static void main(String[] args) throws FileNotFoundException,
			IOException, ClassNotFoundException {
		File file = new File("D:/hahaha.txt");
		write(file);
		read(file);
	}

	/*
	 * 序列化输出流
	 */
	public static void write(File file) throws FileNotFoundException,
			IOException {
		// 创建流
		ObjectOutputStream out = new ObjectOutputStream(
				new BufferedOutputStream(new FileOutputStream(file)));
		// 准备数据
		Person p = new Person("张三", 1);
		int[] arr = { 1, 2, 3, 4, 5 };
		// 写数据
		out.writeObject(p);
		out.writeObject(arr);
		// 关闭 = flush + clear + close
		out.close();
	}

	/*
	 * 反序列化输入流
	 */
	public static void read(File file) throws FileNotFoundException,
			IOException, ClassNotFoundException {
		// 创建流
		ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(
				new FileInputStream(file)));

		// 读取
		Object obj = in.readObject();
		if (obj instanceof Person) {
			Person p = (Person) obj;
			System.out.println(p.toString());
		}
		Object ob = in.readObject();
		if (ob instanceof int[]) {
			int[] arr = (int[]) ob;
			System.out.println(Arrays.toString(arr));
		}

		// 关闭
		in.close();
	}
}

class Person implements Serializable {
	private String name; // 名字
	private int gender; // 性别

	public Person(String name, int gender) {
		super();
		this.name = name;
		this.gender = gender;
	}

	public String getName() {
		return name;
	}

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

	public int getGender() {
		return gender;
	}

	public void setGender(int gender) {
		this.gender = gender;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", gender=" + gender + "]";
	}
}
  • 1.3.2 反序列化输入流

 

  • 2. 反射(reflection)

“程序运行时,允许改变程序结构或变量类型,这种语言称为动态语言”,如Python,Ruby是动态语言;显然C++,Java,C#不是动态语言,但是JAVA有着一个非常突出的动态相关机制:Reflection

JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制

  • 2.1 获取对象

 * 反射是发生在程序的运行期间
 *     
 * 在类加载的时候,在内存中就会存在一个这个类的Class对象,对象中存在这个类的所有信息(方法,属性,构造器...)
 * 在创建的对象的时候,得到的是这个Class对象的一个镜像|复制体
 * 如果拿到了类型Class类的实例,就可以进行一切操作
 * 
 * 如何获取Class对象|源头:
 *     1.类名.class
 *  2.对象.getClass()
 *  3.Class.forName("包名+类名");  ----最推荐

package day16.reflection;

public class ReflectDemo07 {
	public static void main(String[] args) throws ClassNotFoundException {
		// 1.类名.class
		Class ref = ReflectDemo07.class;
		System.out.println(ref);
		// 对象.getClass()
		ReflectDemo07 ref2 = new ReflectDemo07();
		Class<?> r = ref2.getClass();
		System.out.println(r);
		// 3.Class.forName("包名+类名");
		Class<?> r2 = Class.forName("day16.reflection.ReflectDemo07");
		System.out.println(r2);
		
		test("Apple");
	}

	static void test(String str) throws ClassNotFoundException {
		if("Apple".equals(str)){
//			new Apple();
			Class.forName("com.relect.Apple");
		}else{
//			new Banana(); //香蕉
			Class.forName("com.relect.Banana");
		}
	}
}
  • 2.2 获取构造器

 * 获取构造器:
 * Constructor<T> getConstructor(Class<?>... parameterTypes) 
          返回一个 Constructor 对象,它反映此 Class 对象所表示的类的指定公共构造方法。 
   Constructor<?>[] getConstructors() 
          返回一个包含某些 Constructor 对象的数组,这些对象反映此 Class 对象所表示的类的所有公共构造方法。 
   Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) 
          返回一个 Constructor 对象,该对象反映此 Class 对象所表示的类或接口的指定构造方法。 
   Constructor<?>[] getDeclaredConstructors()  

package day16.reflection;

import java.lang.reflect.Constructor;
import java.util.Arrays;

public class ReflectDemo08{
	public static void main(String[] args) throws NoSuchMethodException, SecurityException {
		//获取对象
		Class ref = ReflectDemo08.class;
		//获取指定公共构造器
/*		Constructor con =ref.getConstructor(String.class);
		System.out.println(con);
		
		//获取所有公共构造器
		Constructor[] cons = ref.getConstructors();
		System.out.println(Arrays.toString(cons));*/
		
		//获取指定的私有构造器
		Constructor con2=ref.getDeclaredConstructor();
		System.out.println(con2);
		//获取所有的私有构造器
		Constructor[] con2s=ref.getDeclaredConstructors();
		System.out.println(Arrays.toString(con2s));
	}
	
	
	private String name;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	private ReflectDemo08() {
		
	}
	private ReflectDemo08(String name) {
		this.name = name;
	}
	
}
  • 2.3 获取属性(字段)

     * 获取字段:
     * 
     *      Field[] getDeclaredFields() 
     *             返回 Field 对象的一个数组,这些对象反映此 Class 对象所表示的类或接口所声明的所有字段。 
     *       Field getField(String name) 
     *             返回一个 Field 对象,它反映此 Class 对象所表示的类或接口的指定公共成员字段。 
     *       void set(Object obj, Object value) 
     *             将指定对象变量上此 Field 对象表示的字段设置为指定的新值。 
     *       Object get(Object obj) 
     *             返回指定对象上此 Field 表示的字段的值。

package day16.reflection;
/*
 * java.lang.reflect.Modifier 
 public static final int ABSTRACT 1024 
 public static final int FINAL 16 
 public static final int INTERFACE 512 
 public static final int NATIVE 256 
 public static final int PRIVATE 2 
 public static final int PROTECTED 4 
 public static final int PUBLIC 1 
 public static final int STATIC 8 
 public static final int STRICT 2048 
 public static final int SYNCHRONIZED 32 
 public static final int TRANSIENT 128 
 public static final int VOLATILE 64 

 */
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectDemo10 extends Fu implements I1,I2{
	private String name;
	public  int age;
	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException, SecurityException, NoSuchMethodException {
		//getField();
		getMethods();
	}

	public static void getField() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException {
		Class cls = Class.forName("day16.reflection.ReflectDemo10");
		ReflectDemo10 ref = (ReflectDemo10) cls.newInstance();
		
		Field[] fields = cls.getDeclaredFields();
		for (Field f : fields) {
			System.out.println(f.getName());//获取字段名名字
		}
		Field f = cls.getField("age");
		f.set(ref, 100);
		System.out.println(ref.age);
		
		//使用Person类中的私有的属性
		Class c = Person.class;
		Person ref1 = (Person) c.newInstance();
		Field f1 = c.getDeclaredField("gender");
		//打开权限
		f1.setAccessible(true);
		f1.set(ref1, 2);
		System.out.println(f1.get(ref1));
		//关闭权限
		f1.setAccessible(false);
	}
  • 2.4 获取方法

 * 2.获取方法:Method[]   getDeclaredMethods()

/*
	 * 2.获取方法:Method[]   getDeclaredMethods()
	 */
	public static void getMethods() throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{
		Class cls = Class.forName("day16.reflection.ReflectDemo10");
		ReflectDemo10 ref = (ReflectDemo10) cls.newInstance();
		Method[] methods = cls.getDeclaredMethods();
		for(Method m:methods){
			System.out.println(m);//获取方法名名字
			
		methods[4].invoke(ref, "刘文旭");
		}
		System.out.println(ref.getName());
		
		//其他类中的私有方法
		Class c = Person.class;
		Person ref1 = (Person) c.newInstance();
		
		Method m = c.getDeclaredMethod("test");
		m.setAccessible(true);
		m.invoke(ref1);
		
		Method m2 = c.getDeclaredMethod("testStatic");
		m2.invoke(null);
		m.setAccessible(false);
		
	}

	public ReflectDemo10() {
		
	}

	public ReflectDemo10(String name) {
		super();
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	 void test(){
		System.out.println("哈哈哈哈啊哈哈哈哈");
	}
	
}
class Person{
		private int gender;
		private void test(){
			System.out.println("Person   private    test()");
		}
		
		static void testStatic(){
			System.out.println("testStatic");
		}
	}
  • 2.5 创建类型对象根据Class对象

/*
 * java.lang.reflect.Modifier 
 public static final int ABSTRACT 1024 
 public static final int FINAL 16 
 public static final int INTERFACE 512 
 public static final int NATIVE 256 
 public static final int PRIVATE 2 
 public static final int PROTECTED 4 
 public static final int PUBLIC 1 
 public static final int STATIC 8 
 public static final int STRICT 2048 
 public static final int SYNCHRONIZED 32 
 public static final int TRANSIENT 128 
 public static final int VOLATILE 64 

 */
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class ReflectDemo09 extends Fu implements I1,I2{
	private String name;
	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		//createObj();
		//getFu();
		getMo();
	}
	/*
	 * 1.通过反射创建对象
	 */
	public static void createObj() throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		//1.获取类的Class对象,调用方法  newInstance()创建对象,调用空构造,空构造一般都给
		Class ref = Class.forName("day16.reflection.ReflectDemo09");
		ReflectDemo09 ref2 = (ReflectDemo09)ref.newInstance();
		ref2.test();
		
		//2.先获取到对应的构造器对象,然后通过这个构造器创建对象  T newInstance(Object... initargs)
		Constructor[] con = ref.getConstructors();
		for (Constructor c : con) {
			System.out.println(c);
		}
		ReflectDemo09 ref4 = (ReflectDemo09) con[0].newInstance("王五");
		System.out.println(ref4.getName());
	}
  • 2.6 获取父类(父接口)的Class对象

/*
	 * 2.获取父类|父接口的Class对象
	 */
	public static void getFu() throws ClassNotFoundException, InstantiationException, IllegalAccessException{
		//1.获取类的Class对象
		Class ref = Class.forName("day16.reflection.ReflectDemo09");
		Class clsFu = ref.getSuperclass();
		//2.创建对象,调用方法
		Fu fu = (Fu) clsFu.newInstance();
		fu.test();
		
		Class[] cls = ref.getInterfaces();
		for (Class class1 : cls) {
			System.out.println(class1);
		}
	}
  • 2.7 获取修饰符

/*
	 * 3.获取修饰符
	 */
	public static void getMo() throws ClassNotFoundException {
		//1.获取类的对象
		Class ref = Class.forName("day16.reflection.ReflectDemo09");
		int i = ref.getModifiers();
		System.out.println(i);
	}

	public ReflectDemo09() {
		
	}

	public ReflectDemo09(String name) {
		super();
		this.name = name;
	}

	public String getName() {
		return name;
	}

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

class Fu{
	void test(){
		System.out.println("我是父类的test方法..");
	}
}

interface I1{
	
}
interface I2{
	
}
  • 3. 枚举类

 * 枚举类
 *     1.所有的枚举类都隐式的继承了java.lang.enum抽象类
 *     2.枚举也是类,枚举中的的所有成员都是类型的对象|实例 ,成员默认是public static final

package day16.io;

public class EnumDemo06 {
	public static void main(String[] args) {
		Weekday sun=Weekday.Sun;
		//1.返回此枚举常量的名称
		System.out.println(sun.name());
		//2.返回枚举常量的索引
		System.out.println(sun.ordinal() );
		//3.values() 返回当前枚举类的所有属性
		Weekday[] week=sun.values();
		for(Weekday w:week){
			System.out.print(w+"  ");
		}
	}
}

enum Weekday{
	Sun,Mon,Tues,Wed,Thur,fri,Sat;
	
	//可以存在成员方法
	public void test(){
		
	}
}

//class Weekday{
//	public static final Weekday Sun = new Weekday();
//}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值