java中的class类_Java Class类

java中的class类

In our previous topic, we discussed about how to load a class at runtime using various ways. Here we will see how to get metadata of that class, its methods and fields.

在上一个主题中,我们讨论了如何在运行时使用各种方式加载类。 在这里,我们将看到如何获取该类,其方法和字段的元数据。

Class is a final class in java.lang package which extends Object class. Instance of this class represents classes and interfaces in a running Java application. It is used to analyze and change dynamic behaviour of a class at runtime.

Classjava.lang包中的最终类,它扩展了Object类。 此类的实例表示正在运行的Java应用程序中的类和接口。 它用于在运行时分析和更改类的动态行为。

java.lang.Class类的方法 (Methods of java.lang.Class class)

This class defines several methods using which we can get information about methods, constructors, modifiers and members of a class at runtime.

此类定义了几种方法,通过这些方法,我们可以在运行时获取有关类的方法构造函数修饰符成员的信息。

forName() (forName())

This method takes fully qualified name of classes or interface as its argument and returns instance of the class assocaited with it.

此方法将类或接口的完全限定名称作为其参数,并返回与之关联的类的实例。

句法
staticClass < ?> forName(String className )

示例:获取类元数据

(Syntax

Example: Fetch Class Metadata

)

To get metadata of a class, first we need to load the class using class.forName() method and then use Class methods. In this example, we used getName() method to get name of the class and getDeclaredFields() to get all the fields of the class. See the below example.

要获取类的元数据,首先我们需要使用class.forName()方法加载类,然后使用Class方法。 在此示例中,我们使用getName()方法获取类的名称,并使用getDeclaredFields()获取类的所有字段。 请参见以下示例。

package myjavaproject;

import java.util.Arrays;

// Employee Class
class Employee{

  // Fields 
  int empId;
  String name;
  
  // Constructor
  Employee(int empId, String name){
    this.empId = empId;
    this.name = name;
  }
  
  // Method
  void showInfo() {
    System.out.println("Employee Id: "+empId);
    System.out.println("Employee Name: "+name);
  }
}

class Demo{
  public static void main(String[] args) throws ClassNotFoundException {
    
    // Employee class
    Class name = Class.forName("myjavaproject.Employee");
    // Get class Name
    System.out.println(name.getName());
    // Get Package
    System.out.println(name.getPackageName());
    System.out.println(name.getTypeName());
    Arrays.stream(name.getDeclaredConstructors()).forEach(System.out::println);
    Arrays.stream(name.getDeclaredFields()).forEach(System.out::println);
    Arrays.stream(name.getDeclaredMethods()).forEach(System.out::println);
  }
}

myjavaproject.Employee myjavaproject myjavaproject.Employee myjavaproject.Employee(int,java.lang.String) int myjavaproject.Employee.empId java.lang.String myjavaproject.Employee.name void myjavaproject.Employee.showInfo()

myjavaproject.Employee myjavaproject myjavaproject.Employee myjavaproject.Employee(int,java.lang.String)int myjavaproject.Employee.empId java.lang.String myjavaproject.Employee.name void myjavaproject.Employee.showInfo()

示例:获取字段元数据 (Example: Get Field Metadata)

To deal with class fields, Java provides a Field class which is located into java.lang.reflect package. This class contains methods that helps to get metadata of a field. In this example, you can see that we used class.forName to load the class and then Field class to get metadata of the class.

为了处理类字段,Java提供了一个Field类,该类位于java.lang.reflect包中。 此类包含有助于获取字段元数据的方法。 在此示例中,您可以看到我们使用class.forName加载该类,然后使用Field类获取该类的元数据。

package myjavaproject;

import java.lang.reflect.Field;

// Employee Class
class Employee{

  // Fields 
  int empId;
  String name;
  
  // Constructor
  Employee(int empId, String name){
    this.empId = empId;
    this.name = name;
  }
  
  // Method
  void showInfo() {
    System.out.println("Employee Id: "+empId);
    System.out.println("Employee Name: "+name);
  }
}

class Demo{
  public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException {
    
    // Employee class
    Class name = Class.forName("myjavaproject.Employee");
    // Get Fields metadata
    Field[] field = name.getDeclaredFields();
    for(Field f: field) {
      System.out.print(f.getType()+" ");
      System.out.println(f.getName());
      System.out.println(f.getModifiers());     
    }   
  }
}

int empId 0 class java.lang.String name 0

int empId 0类java.lang.String名称0

示例:获取方法元数据 (Example: Get Method Metadata)

To deal with class methods, Java provides a Method class which is located into java.lang.reflect package. This class contains methods that helps to get metadata of a method. In this example, you can see that we used class.forName to load the class and then Method class to get metadata of the method.

为了处理类方法,Java提供了一个Method类,该类位于java.lang.reflect包中。 此类包含有助于获取方法元数据的方法。 在此示例中,您可以看到我们使用class.forName加载该类,然后使用Method类获取该方法的元数据。

import java.lang.reflect.Method;

// Employee Class
class Employee{

  // Fields 
  int empId;
  String name;
  
  // Constructor
  Employee(int empId, String name){
    this.empId = empId;
    this.name = name;
  }
  
  // Method
  void showInfo() {
    System.out.println("Employee Id: "+empId);
    System.out.println("Employee Name: "+name);
  }
}

class Demo{
  public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException {
    
    // Employee class
    Class name = Class.forName("myjavaproject.Employee");
    // Get method metadata
    Method[] method = name.getDeclaredMethods();
    for(Method m: method) {
      System.out.println(m);
      System.out.println(m.getDefaultValue());
      System.out.println(m.getModifiers());
      System.out.println(m.getName());
      System.out.println(m.getParameterCount());
      System.out.println(m.getReturnType());
    }   
  }
}

void myjavaproject.Employee.showInfo() null 0 showInfo 0 void

void myjavaproject.Employee.showInfo()无效0 showInfo 0无效

示例:获取构造函数元数据 (Example: Get Constructor Metadata)

A class may have several constructors including parameterized and non parameterized as well. Java reflection provides the Constructor class that consists of methods and can be used to get metadata of constructor. In this example, we used constructor class and its methods to get metadata of constructors. See the example below.

一个类可能具有多个构造函数,包括参数化的和非参数化的。 Java反射提供了由方法组成的Constructor类,可用于获取构造函数的元数据。 在此示例中,我们使用了构造函数类及其方法来获取构造函数的元数据。 请参见下面的示例。

package myjavaproject;

import java.lang.reflect.Constructor;
import java.lang.reflect.Parameter;

// Employee Class
class Employee{

  // Fields 
  int empId;
  String name;
  
  // Constructor
  Employee(int empId, String name){
    this.empId = empId;
    this.name = name;
  }
  
  // Method
  void showInfo() {
    System.out.println("Employee Id: "+empId);
    System.out.println("Employee Name: "+name);
  }
}

class Demo{
  public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException {
    
    // Employee class
    Class name = Class.forName("myjavaproject.Employee");
    // Get method metadata
    Constructor[] constructor = name.getDeclaredConstructors();
    for(Constructor c: constructor) {
      System.out.println(c);
      System.out.println(c.getModifiers());
      System.out.println(c.getName());
      System.out.println(c.getParameterCount());
      System.out.println(c.getDeclaringClass());
      Parameter[] parameters = c.getParameters();
      for(Parameter p : parameters) {
        System.out.println(p);
      }
      
      Class[] pt = c.getParameterTypes();
      for(Class s : pt) {
        System.out.println(s);
      }
    }   
  }
}

myjavaproject.Employee(int,java.lang.String) 0 myjavaproject.Employee 2 class myjavaproject.Employee int arg0 java.lang.String arg1 int class java.lang.Strings

myjavaproject.Employee(int,java.lang.String)0 myjavaproject.Employee 2类myjavaproject.Employee int arg0 java.lang.String arg1 int类java.lang.Strings

getConstructors()和getDeclaredConstructors() (getConstructors() and getDeclaredConstructors())

getConstructors() method returns array of Constructors object that represent all the public constructors of the invoking object. Remember, this method only returns public constructors. If you want to see all the declared constructors of a class then use getDeclaredConstructors(). Following is the general syntax of both,

getConstructors()方法返回Constructors对象的数组,这些对象表示调用对象的所有公共构造函数。 请记住,此方法仅返回公共构造函数。 如果要查看类的所有已声明构造函数,请使用getDeclaredConstructors() 。 以下是两者的通用语法,

Constructor< ?>[] getConstructors();
Constructor< ?>[] getDeclaredConstructors();

示例:getConstructors()和getDeclaredConstructors()方法 (Example: getConstructors() and getDeclaredConstructors() method)

Both the methods are used to get class constructors but the getConstructors() returns only public constructors whereas getDeclaredConstructors() returns all the available constructors.

这两种方法都用于获取类构造函数,但是getConstructors()仅返回公共构造函数,而getDeclaredConstructors()返回所有可用的构造函数。

import java.lang.reflect.*;
class Student
{
  public Student(){}
  public Student(String name){}
}

class Test
{
  public static void main(String args[])
  {
    try
    {
      Class c = Class.forName("Student");
      Constructor< Student>[] ct = c.getConstructors();
      for(int i=0; i< ct.length; i++)
      { System.out.println(ct[i]); }
      Constructor< Student>[]cdt = c.getDeclaredConstructors();
      for(int i=0;i< cdt.length;i++)
      { System.out.println(cdt[i]);}
    }
    catch(Exception e)
    { e.printStackTrace();}
  }
}

public Student() public Student(java.lang.String) public Student() public Student(java.lang.String)

public Student()public Student(java.lang.String)public Student()public Student(java.lang.String)

getMethods()和getDeclaredMethods() (getMethods() and getDeclaredMethods())

getMethods() method returns array of Method object that reflect all the public method of invoking object. getDeclaredMethods() returns only the declared methods of the invoking class object. Syntax for both is following,

getMethods()方法返回Method对象的数组,该数组反映所有调用对象的公共方法。 getDeclaredMethods()仅返回调用的类对象的已声明方法。 两者的语法如下:

Method< ?>[] getMethods();
Method< ?>[] getDeclaredMethods();

示例:getDeclaredMethods()方法 (Example: getDeclaredMethods() method)

Lets take an example in which we are using getDeclaredMethods() method to get all the declared methods in the class. See the below example.

让我们举一个例子,其中我们使用getDeclaredMethods()方法获取类中所有已声明的方法。 请参见以下示例。

import java.lang.reflect.*;
class Student
{
  public void show(){}
  void display(){}
}

class Test
{
  public static void main(String args[])
  {
    try
    {
      Class c = Class.forName("Student");
      Method md[] = c.getDeclaredMethods();
      for(int i=0; i< md.length; i++ )
      { System.out.println(md[i]); }
    }
    catch(Exception e)
    { e.printStackTrace();}
  }
}

public void Student.show() void Student.display()

公共void Student.show()void Student.display()

getFields()和getDeclaredFields() (getFields() and getDeclaredFields())

getFields() returns an array containing Field objects reflecting all the accessible public members of the class or interface represented by this Class object. getDeclaredFields() returns array of Field objects reflecting all the fields declared by the class or interface represented by this Class object.

getFields()返回一个包含Field对象的数组,该对象反映此Class对象表示的类或接口的所有可访问的公共成员。 getDeclaredFields()返回Field对象的数组,该数组反映由该Class对象表示的类或接口声明的所有字段。

Field< ?>[] getFields();
Field< ?>[] getDeclaredFields();

示例:getFields()和getDeclaredFields()方法 (Example: getFields() and getDeclaredFields() method)

To get fields of a class, we can use either getFields() or getDeclaredFields() method. Both returns fields except that getFields returns only public fields. See the below example.

要获取类的字段,我们可以使用getFields()getDeclaredFields()方法。 两者都返回字段,但getFields仅返回公共字段。 请参见以下示例。

import java.lang.reflect.*;
class Student
{
  public  String name;
  int roll;
}

class Test
{
  public static void main(String args[])
  {
    try
    {
      Class c = Class.forName("Student");
      Field ff[] = c.getFields();
      for(int i=0; i< ff.length; i++)
      { System.out.println(ff[i]); }
      Field f[] = c.getDeclaredFields();
      for(int i=0;i< f.length; i++)
      { System.out.println(f[i]);  }
    }
    catch(Exception e)
    { e.printStackTrace();}
  }
}

public java.lang.String Student.name public java.lang.String Student.name int Student.roll

public java.lang.String Student.name public java.lang.String Student.name int Student.roll

翻译自: https://www.studytonight.com/java/reflection-classes.php

java中的class类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值