The single-element enumeration class is used to implement the singleton mode.

Source: Internet
Author: User

The single-element enumeration class is used to implement the singleton mode.

In the previous article "terminator of Singleton mode -- setAccessible (true)", we introduced the shortcomings of the traditional Singleton mode. Although the singleton mode of enumeration classes has not been widely used, however, in objective java, single-element enumeration classes have been recognized as the best way to implement the singleton mode.

Below is a demo to demonstrate that there is only one element of the enumeration class, which can also be written into the enumeration class.

package go.derek;public enum EnumSingleton {instance;public void doSomething(){System.out.println("do something");}}

The test class is as follows:

Package go. derek; import java. lang. reflect. constructor; import java. lang. reflect. invocationTargetException; public class Test {public static void main (String [] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {Constructor <?> [] Array = EnumSingleton. class. getDeclaredConstructors (); for (Constructor <?> C: array) {c. setAccessible (true); // an exception c. newInstance () ;}} is thrown here ();}}}
The running result is as follows:

Exception in thread "main" java. lang. IllegalArgumentException: Cannot reflectively create enum objects
At java. lang. reflect. Constructor. newInstance (Constructor. java: 521)
At go. derek. Test. main (Test. java: 13)

It can be seen that enumeration objects cannot be created through reflection. Therefore, this Singleton mode can defend against reflection attacks by malicious clients. In addition, the singleton mode of enumeration classes does not have to worry about multiple instance creation during deserialization.


Color is a struct of the enumeration type. I only assigns the elements in the enumeration to it. How can this be forced conversion?

On 32 machines, no matter how many enumerated members are defined, the enumeration type is 4 bytes in size, the same as int, which is the basis for mutual conversion between the enumeration type and int.
You can assign values to the int type directly, but not to the int type directly (only mandatory type conversion is required ).
Example program:

Void main ()
{
Enum open_modes {input, output, append };
Enum Forms {shape = 1, sphere, cylinder, polygon };

Cout <sizeof (open_modes) <endl;
Cout <sizeof (Forms) <endl;
Cout <sizeof (int) <endl;

// Open_modes om = 1; // error
Open_modes om = (open_modes) 1;
Int t = open_modes: input;
Int k = om;
Cout <om <"<t <" "<k <endl;

Open_modes om2 = (open_modes) 4;
Cout <om2 <endl;
}

How to print enumeration elements in a loop

Use the values method of Enumeration type to retrieve all enumeration items.

The following is an example.

Public class EnumTest {
Enum Country {
China, America, and Japan;
}

Public static void main (String [] args ){
For (Country country: Country. values ()){
System. err. println (country );
}
}
}
============================================

To yoyo76ke
Why is there a problem. I posted the results after testing... please read carefully if there is any difference between my program and your program, and then question it again .. why are there errors in the same thing ..

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.