`

Java Create Instance Method

 
阅读更多

Java Create Instance Method

 

1.Normal
Student stu1 = new Student(1, "NameNornal", 1);


2. Reflection

Student stu1 = Class.forName("com.test.vo.Student").newInstance();

 

See details in code

/**
 * This test class is used for Creating Object Instance.
 * 
 * https://github.com/jnh1983/CoreJava/blob/master/src/com/test/classes/CreateInstanceTest.java
 * 
 * @author Joey
 */
public class CreateInstanceTest {

	public static void main(String[] args) throws Exception{
		// 1. Normal
		Student stu1 = new Student(1, "NameNornal", 1);
		print(stu1);
		
		// 2. Reflection
		Student stu2 = (Student) Class.forName("com.test.vo.Student")
				.getConstructor(Integer.TYPE, String.class, Integer.TYPE)
				.newInstance(2, "NameReflection", 1);
		print(stu2);
		
		// 3. Factory Pattern
		Student stu3 = (Student) PersonFactory.getPerson(PersonFactory.TYPE_STUDENT, null);
		print(stu3);
		
		// 4. Object Clone Method
		Student stu4 = stu1.clone();
		print(stu4);
	}

	public static void print(Student p_stu){
		System.out.println(p_stu);
	}
}

 

output:

Student [id=1, name=NameNornal, classId=1]
Student [id=2, name=NameReflection, classId=1]
Student [id=-1, name=nameFactory, classId=-1]
Student [id=0, name=Clone-NameNornal, classId=1]

 

分享到:
评论

相关推荐

    Java常用设计模式(SingleTon、FactoryMethod、AbstractFactory)

    这里我们将深入探讨三种常见的Java设计模式:单例(Singleton)、工厂方法(Factory Method)和抽象工厂(Abstract Factory)。 **单例模式(Singleton)** 单例模式确保一个类只有一个实例,并提供一个全局访问点...

    java7帮助文档

    Type Inference for Generic Instance Creation Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods The try-with-resources Statement Catching Multiple...

    Java动态代理两种实现方式

    MyClass proxyInstance = (MyClass) enhancer.create(); proxyInstance.myMethod(); ``` ### 比较与选择 JDK动态代理简单易用,但要求目标对象必须实现至少一个接口,这限制了它的使用场景。而Cglib则不需要目标...

    JavaChineseCalendar

    You have to use the **建立** static method provided by **農曆** class to create a **農曆** instance. You can pass the year, month and the days of the month in Gregorian calendar as parameters to **...

    java动态特性eval

    在模拟`eval()`功能时,我们可能需要使用`Class.forName()`加载类,`Method.invoke()`执行方法,或者`Constructor.newInstance()`创建对象。通过这些反射方法,我们可以解析字符串并执行相应的Java代码。 2. **Java...

    Java_for_the_Web_with_Servlets

    - **How a Servlet Works**: When a request is sent to a servlet, the servlet container creates a new instance of the servlet if one does not already exist. The `init()` method initializes the servlet, ...

    flash与java交互的方法

    var wasSuccessful:Boolean = ExternalInterface.addCallback(methodName, instance, method); var txtField:TextField = this.createTextField("txtField", this.getNextHighestDepth(), 0, 0, 200, 50); ...

    javaapi和源码-varcode:在运行时动态生成,编译和运行.java源

    create instance Object dynamicModel = _model.instance(); // 3) call a method on the dynamic instance String id1 = (String)Java.call( dynamicModel, "createId" ); // 4) export .java & .class files: // ...

    java调用WebService(客户端)整理.pdf

    Object response = client.invoke("methodName", params); ``` 4. **Documentation方式** Documentation方式通常用于获取WebService的服务描述文档,如WSDL。在ASP.NET环境中,当直接请求一个`.asmx`页面时,会...

    Java反射机制 深入浅出

    public static Object create(String className) throws Exception { return Class.forName(className).newInstance(); } } ``` #### 八、代理模式 反射技术也是实现动态代理的基础。动态代理允许我们在不...

    Java自定义异常案例--ExceptionManager(java源码)

    * This static method create an instance of the ExceptionManager by invoking the * constructor <code>ExceptionManager(String msg)</code>. * * @param msg The message will pass the specified ...

    jOOR - Fluent Reflection in Java jOOR is a very simple flu.zip

    在Java中,标准的反射API位于`java.lang.reflect`包下,包括`Class`, `Constructor`, `Method`和`Field`等类。这些类提供了获取类信息、创建对象、调用方法和访问字段的能力。然而,标准API的使用方式往往较为繁琐,...

    Java邮件开发Fundamentals of the JavaMail API

    You use the package to create Mail User Agent (MUA) type programs, similar to Eudora, pine, and Microsoft Outlook. The API's main purpose is not for transporting, delivering, and forwarding ...

    JavaFunctors:Java SE 7中的Functor实现

    动机作为Java SE 7的内置功能,缺少函子(或函数对象),建议的回调方法是使用接口。...}}...// create an instance of SomeClassSomeClass instance = new SomeClass();// prepare the arguments for the method s

    Java中的反射实现数据库操作

    对于数据库操作,我们通常会有一个包含CRUD(Create、Read、Update、Delete)方法的通用DAO(Data Access Object)类。通过反射,我们可以动态地调用这些方法,处理任何类型的实体对象。例如,一个通用的`save()`...

    JAVA英文常用词汇.doc

    21. **Data Definition Language (DDL)**:用于创建和修改数据库结构的语言,如 SQL 中的 CREATE 和 ALTER 语句。 22. **Data source**:存储数据的来源,可能是一个数据库、文件或其他数据提供者。 23. **Data ...

    Java语言程序设计基础篇课后题答案-Chapter18BinaryI_O.pdf

    13. To read a binary file using `FileInputStream`, you would typically create an instance of `FileInputStream`, passing the file path as a parameter, then call the `read()` method repeatedly to read ...

    servlet2.4doc

    Overrides the standard java.lang.Object.clone method to return a copy of this cookie. containsHeader(String) - Method in class javax.servlet.http.HttpServletResponseWrapper The default behavior of ...

    Unity调用JAR例子方法非常简单.zip

    Debug.LogError("Failed to create Java object instance."); } ``` 步骤四:处理返回值和参数 3. 如果Java方法有返回值或需要参数,我们需要适当地传递和接收。例如,如果`doSomething`方法返回一个字符串,我们...

Global site tag (gtag.js) - Google Analytics