isInstance and isAssignableFrom
obj instanceof Class
Determine whether obj is a subclass of Class or Class
clazz.isInstance(obj)
Determine whether obj can be cast to clazz type, that is, whether obj is a subclass of clazz or clazz
clazz1.isAssignableFrom(clazz2)
Return True if clazz2 and clazz1 are the same or clazz1 is the parent class of clazz2, otherwise return Flase
static class Parent{}static class Son extends Parent{}public static void main(String[] args) {Parent parent=new Parent();Son son=new Son();Assert.assertTrue(son instanceof Son);Assert.assertTrue(son instanceof Parent);Assert.assertFalse(parent instanceof Son);Assert.assertTrue(Son.class.isInstance(son));Assert.assertFalse(Son.class.isInstance(parent));Assert.assertTrue(Parent.class.isInstance(son));Assert.assertTrue(Son.class.isAssignableFrom(Son.class));Assert.assertFalse(Son.class.isAssignableFrom(Parent.class));Assert.assertTrue(Parent.class.isAssignableFrom(Son.class));} Modifier.isTransient(field.getModifiers())
When serializing objects using Java's own method, transient member variables will not be serialized. Sensitive information such as bank passwords are not allowed to be serialized to disk or transmitted on the network.
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;public class Account implements Serializable{private static final long serialVersionUID = 2103161633120805900L;private String name;private transient String password;public Account(String n,String p){this.name=n;this.password=p;}@Override public String toString(){return "["+this.name+"]/t["+this.password+"]";}//Serialize public static byte[] serialize(Object object) {ObjectOutputStream oos = null;ByteArrayOutputStream baos = null;try {baos = new ByteArrayOutputStream();oos = new ObjectOutputStream(baos);oos.writeObject(object);oos.close();byte[] bytes = baos.toByteArray();return bytes;}catch (Exception e) {e.printStackTrace();}return null;}// Deserialize public static Object deserialize(byte[] bytes) {ByteArrayInputStream bais = null;try {bais = new ByteArrayInputStream(bytes);ObjectInputStream ois = new ObjectInputStream(bais);Object rect=ois.readObject();ois.close();return rect;}catch (Exception e) {e.printStackTrace();}return null;}public static void main(String[] args) throws IOException {Account inst=new Account("orisun","123456");System.out.println("Before serialization"+inst);byte[] datas=serialize(inst);Account inst2=(Account)deserialize(datas);System.out.println("Serialized"+inst2);}}Summarize
The above is the entire content of this article about some method example codes on Java classes and members. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!