Java Reflection Learning notes three ways to instantiate 1--class class

Source: Internet
Author: User
Tags reflection
Package Com.zq.demo;

Import java.util.Date;

public class Demo1 {public
     static void Main (string[] args) {
		   Demo1 d=new Demo1 ();
		   class<? Extends demo1> class1 = D.getclass ();
		   System.out.println (Class1.getname ()); 
		   System.out.println (Class1.getsimplename ());
		   Date Date=new date ();
           class<? Extends date> Class2 = Date.getclass ();
           System.out.println (Class2.getname ());
           System.out.println (Class2.getsimplename ());
     }
Output Result: Com.zq.demo.Demo1
Demo1
Java.util.Date

Date

Creates an object of class type by calling the GetClass () method from the object. This is one of the ways in which class objects are instantiated. But this approach is rarely used.


Second.

Package Com.zq.demo;

public class Demo2 {public
	static void Main (string[] args) {
		class cls = Java.util.Date.class;
		The loaded byte code is encapsulated into a class object

		String name = Cls.getname ();
		SYSTEM.OUT.PRINTLN (name);
		System.out.println (Cls.getsimplename ());

	}


Instantiate the class object by class name and class. There's more to this way.


Third.

Package Com.zq.demo;

public class Demo3 {public
  static void Main (string[] args) {
	 try {
		class<?> name = Class.forName ("ja Va.util.Date ");
		System.out.println (Name.getname ());
		System.out.println (Name.getsimplename ());
	} catch (ClassNotFoundException e) {
		//TODO auto-generated catch block
		e.printstacktrace ();
	}
}
}
Results of output:

Java.util.Date
Date

This approach is to instantiate a class type by Class.forName ("Class full Name"). This approach is more common in the framework, and is also used in JDBC technology to load the required drivers into the container.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.