Several ways to instantiate a new instance

package com.fish.study.instance;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * Created by Gan on 2017/7/1 0001.
 */
public class PersonBeanInstantiate {

    public static void main(String[] args){
        PersonBean personBean = null;
        // Use new
        personBean = newBean();
        // Use Constructor
        constructorBean();
        // Use classForname(Reflect)
        fornameBean();
        // Use Clone
        cloneBean(personBean);
        // Use Serializable
        serializableBean(personBean);
    }

    private static PersonBean newBean(){
        PersonBean personBean = null;
        try {
            printStatus(InstantiateType.NEW, Status.BEGIN);
            personBean = new PersonBean();
            printStatus(InstantiateType.NEW,Status.FINISHED);
        }catch (Exception e){
        }finally {
            return personBean;
        }
    }

    private static void constructorBean() {
        try {
            printStatus(InstantiateType.CONSTRUR,Status.BEGIN);
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            Class clazz = classLoader.loadClass(PersonBean.class.getName());
            Constructor constructor = clazz.getConstructors()[0];
            constructor.newInstance();
            printStatus(InstantiateType.CONSTRUR,Status.FINISHED);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private static void serializableBean(PersonBean personBean) {
        try {
            File file = new File("PersonBean.out");
            ObjectOutputStream oout =  new ObjectOutputStream(new FileOutputStream(file));
            oout.writeObject(personBean);
            oout.close();

            printStatus(InstantiateType.SERIALIZE,Status.BEGIN);
            ObjectInputStream oin = new ObjectInputStream(new FileInputStream(file));
            Object newPerson = oin.readObject();
            oin.close();
            printStatus(InstantiateType.SERIALIZE,Status.FINISHED);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static void cloneBean(PersonBean personBean) {
        try {
            printStatus(InstantiateType.CLONE,Status.BEGIN);
            PersonBean personBeanClone =  (PersonBean) personBean.clone();
            printStatus(InstantiateType.CLONE,Status.FINISHED);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }

    private static void fornameBean() {
        try {
            printStatus(InstantiateType.FORNAME,Status.BEGIN);
            PersonBean personBean = (PersonBean)Class.forName(PersonBean.class.getName()).newInstance();
            printStatus(InstantiateType.FORNAME,Status.FINISHED);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    /**
     * Created by Administrator on 2017/7/1 0001.
     */
    public static class PersonBean implements java.io.Serializable,Cloneable {
        public PersonBean(){
            System.out.println("invoke constructor");
        }

        @Override
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }

        public String getName() {
            return name;
        }

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

        public String getWeight() {
            return weight;
        }

        public void setWeight(String weight) {
            this.weight = weight;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        private String name;
        private String weight;
        private String address;
    }

    private static void printStatus(InstantiateType instantiateType,Status status){
        System.out.println(String.format("Use %-9s to instatiate new instance.....  %-9s  .....",instantiateType.toString(),status.toString()));
    }

    private enum Status{
        BEGIN,FINISHED;
    }

    private  enum InstantiateType{
        NEW,CONSTRUR,FORNAME,CLONE,SERIALIZE;
    }
}

  

时间: 2024-10-12 15:26:37

Several ways to instantiate a new instance的相关文章

android内核剖析学习笔记:AMS(ActivityManagerService)内部原理和工作机制

一.ActivityManagerService提供的主要功能: (1)统一调度各应用程序的Activity (2)内存管理 (3)进程管理 二.启动一个Activity的方式有以下几种: (1)在应用程序中调用startActivity启动指定的Activity (2)在Home程序中单击一个应用图标,启动新的Activity (3)按"Back"键,结束当前Activity,返回到上一个Activity (4)长按"Home"键,显示出当前正在运行的程序列表,从

Database ORM

Database ORM Introduction Basic Usage Mass Assignment Insert, Update, Delete Soft Deleting Timestamps Query Scopes Relationships Querying Relations Eager Loading Inserting Related Models Touching Parent Timestamps Working With Pivot Tables Collection

Level shifting a +/- 2.5V signal to 0 - 5V

Google : Op-Amp Level Shifter Level shifting a +/- 2.5V signal to 0 - 5V I have a front end module that generates an (ECG) signal that varies from +/-2.5 V. I want to shift this signal to 0 - 5V. What is the best way to do this? First thing to try is

ContentProvider学习笔记

一.什么ContentProvider 二.如何使用ContentProvider 三.沙场练兵-实例操练 四.深入理解ContentProvider原理 为什么使用ContentProvider可以实现跨进程的通讯,第一反应肯定是这货和binder有关,因为android中只有稍微跟跨进程搭上边的,必定想到binder. 下面就来分析ContentProvider是怎么一步一步利用binder实现跨进程通信的: 1.首先你得创建一个ContentProvider运行在进程A,如上篇博客 And

redis该如何分区-译文(原创)

写在最前,最近一直在研究redis的使用,包括redis应用场景.性能优化.可行性.这是看到redis官网中一个链接,主要是讲解redis数据分区的,既然是官方推荐的,那我就翻译一下,与大家共享. Partitioning: how to split data among multiple Redis instances. 分区:如何把数据存储在多个实例中. Partitioning is the process of splitting your data into multiple Redi

octobercms数据库使用

运行原始SQL查询 //运行select查询 $users = Db::select('select * from users where active = ?', [1]); 传递给该select方法的第一个参数是原始SQL查询,而第二个参数是需要绑定到查询的任何参数绑定.通常,这些是where子句约束的值.参数绑定提供了针对SQL注入的保护. 该select方法将始终返回一个array结果.数组中的每个结果将是一个PHP stdClass对象,允许您访问结果的值: foreach ($use

From Apprentice To Artisan 翻译 04

Reflect Resolution 反射解决方案 One of the most powerful features of the Laravel container is its ability to automatically resolve dependencies via reflection. Reflection is the ability to inspect a classes and methods. For example, the PHP ReflectionClass

Hystrix使用详解

原文参考:http://hot66hot.iteye.com/blog/2155036 一:为什么需要Hystrix? 在大中型分布式系统中,通常系统很多依赖(HTTP,hession,Netty,Dubbo等),如下图: 在高并发访问下,这些依赖的稳定性与否对系统的影响非常大,但是依赖有很多不可控问题:如网络连接缓慢,资源繁忙,暂时不可用,服务脱机等. 如下图:QPS为50的依赖 I 出现不可用,但是其他依赖仍然可用. 当依赖I 阻塞时,大多数服务器的线程池就出现阻塞(BLOCK),影响整个线

Rogue BoardManager 自动成成内外墙 和食物 敌人

using UnityEngine; using System; using System.Collections.Generic; //Allows us to use Lists.允许使用数组 using Random = UnityEngine.Random; //使用unity自己的随机引擎 namespace Completed { public class BoardManager : MonoBehaviour { // Using Serializable allows us t