java对象转字节数组,获取泛型类

时间:2021-09-29 06:21:47
对象转字节数组,字节数组在恢复成对象
Test.java
class Test {
public static void main(String args[]) throws IOException, ClassNotFoundException {
TestObject to=new TestObject();
to.setAge();
to.setName("lisi");
ByteArrayOutputStream byt=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(byt);
oos.writeObject(to); byte oArr[]=byt.toByteArray();
ByteArrayInputStream bis=new ByteArrayInputStream(oArr);
ObjectInputStream obs=new ObjectInputStream(bis);
TestObject to1= (TestObject) obs.readObject(); System.out.println(to1.getName());
System.out.println(to1.getAge());
}
}
TestObject.java
public class TestObject implements Serializable {
private String name;
private int age; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
}
}

获取泛型类

public class Test<T> {
private Type entityClass;
public Son() {
getSuperclassTypeParameter();
} public void getSuperclassTypeParameter() {
Type superclass = getClass().getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("Missing type parameter.");
} else {
ParameterizedType parameterized = (ParameterizedType)superclass;
System.out.println(parameterized);
}
}
public static void main(String args[]) {
Son<AuthenticatorUser> s= new Son<AuthenticatorUser>(){}; }
}