当前位置:网站首页 > Java教程 > 正文

java反射字段教程



import java.lang.reflect.Field ;
import java.lang.reflect.Method ;
import java.lang.reflect.Constructor ;

public class

ReflectionExample

{

public static void

main

( String [ ]

args

) throws Exception {

// 获取 Class 对象

Class

<?>

clazz

=

Car.

class ;

// 创建 Car 对象

Constructor

<?>

constructor

=

clazz.

getConstructor ( String

.

class

,

int

.

class ) ;

Object

car

=

constructor.

newInstance ( "Toyota"

,

2020 ) ;

// 访问和修改字段

Field

modelField

=

clazz.

getDeclaredField ( "model" ) ;

Field

yearField

=

clazz.

getDeclaredField ( "year" ) ;


// 设置字段为可访问(如果字段是私有的)

modelField.

setAccessible ( true ) ;

yearField.

setAccessible ( true ) ;


// 打印原始字段值

System

.

out

.

println ( "Original Model: " +

modelField.

get (

car

) ) ;

System

.

out

.

println ( "Original Year: " +

yearField.

get (

car

) ) ;


// 修改字段值

modelField.

set (

car,

"Honda" ) ;

yearField.

set (

car,

2024 ) ;


// 打印修改后的字段值

System

.

out

.

println ( "Updated Model: " +

modelField.

get (

car

) ) ;

System

.

out

.

println ( "Updated Year: " +

yearField.

get (

car

) ) ;


// 调用方法

Method

startMethod

=

clazz.

getMethod ( "start" ) ;

startMethod.

invoke (

car

) ;

}
}

class

Car

{

private String

model

;

private int

year

;

public

Car

( String

model,

int

year

) {

this

.

model =

model

;

this

.

year =

year

;

}

public void

start

( ) {

System

.

out

.

println ( "The " +

model

+ " car of year " +

year

+ " is starting." ) ;

}
}

  • 上一篇: 韩国 java教程
  • 下一篇: java模拟登陆教程
  • 版权声明


    相关文章:

  • 韩国 java教程2024-11-22 18:58:02
  • java联盟 教程视频2024-11-22 18:58:02
  • java 画时序图教程2024-11-22 18:58:02
  • java架构 视频教程2024-11-22 18:58:02
  • java教程433集2024-11-22 18:58:02
  • java模拟登陆教程2024-11-22 18:58:02
  • java启动在线教程2024-11-22 18:58:02
  • java 项目式教程2024-11-22 18:58:02
  • java snap教程2024-11-22 18:58:02
  • java字母教程2024-11-22 18:58:02