The difference between getdeclaredfields () and GetFields () in Java

Source: Internet
Author: User

The difference between getdeclaredfields () and GetFields () in Java

Getdeclaredfields () returns all fields in class, including private fields. Example:

Java code
  1. Package Com.test.bean;
  2. Import Java.sql.Timestamp;
  3. Public class Person2 {
  4. private int id;
  5. private int age;
  6. private String PersonName;
  7. private Timestamp birthdate;
  8. Public String identitify;
  9. protected String address;
  10. String phone;
  11. }
  12. @Test
  13. public void Test_getdeclaredfields () {
  14. Field[]fields=person2.  Class.getdeclaredfields ();
  15. For (int i = 0; i < fields.length; i++) {
  16. Field field = Fields[i];
  17. System.out.println (Field.getname ());
  18. }
  19. }

Operation Result:

Id

Age

PersonName

Birthdate

Identitify

Address

Phone

GetFields returns only public fields, that is, fields that have the publicly adornment. Example:

Java code
  1. @Test
  2. public void Test_getdeclaredfields () {
  3. Field[]fields=person2.  Class.getfields ();
  4. For (int i = 0; i < fields.length; i++) {
  5. Field field = Fields[i];
  6. System.out.println (Field.getname ());
  7. }
  8. }

The results of the operation are as follows:

Identitify

Summarize:

(1) Getdeclaredfields () returns all fields in class, including private fields;

(2) GetFields returns only public fields, that is, fields that have publicly decorated

The difference between getdeclaredfields () and GetFields () in Java

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.