当前位置:网站首页 > 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 学习教程推荐2024-11-22 21:42:00
  • java入门教程622024-11-22 21:42:00
  • java自定义编程教程2024-11-22 21:42:00
  • 绿豆java教程2024-11-22 21:42:00
  • java 32k教程2024-11-22 21:42:00
  • 菜鸟教程java学习2024-11-22 21:42:00
  • 菜鸟教程java swing2024-11-22 21:42:00
  • java全系教程2024-11-22 21:42:00
  • java入门教程15讲2024-11-22 21:42:00
  • java带标签教程2024-11-22 21:42:00