gpt4 book ai didi

java - 跨线程反射

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:00:35 25 4
gpt4 key购买 nike

我正在使用一个线程设置多个线程(服务)的设置,一起运行它们以模拟系统的运行,然后在最后加入它们并处理终止等。我的测试运行为其中一项服务并通过 JMS 与其他服务进行通信。对于我的一个测试,我需要访问另一个线程中包含的私有(private)变量。我无法更改在另一个线程中运行的代码,例如添加访问器方法或让它通过 JMS 发送变量。由于框架的设置方式,我也无法将对我想要访问的服务的引用传递到我的测试服务中。

我知道我包含我需要访问的类的线程的名称,并且我可以通过枚举正在运行的线程来获取对该线程的引用,但我不知道如何从线程一旦我得到它。

有没有办法让我使用反射或其他技术在另一个线程中获取对类的引用?

编辑:这是我所处情况的示例:

import java.lang.reflect.Field;

public class Runner
{
/**
* Pretend this is my test class.
*/
public static void main( String[] args )
{
// this is how my test starts up the system and runs the test
runTest( TestService.class );
}

/**
* Instantiate the test service and start up all of the threads in the
* system. Doesn't return until test has completed.
*
* @param testServiceClass
* the class that will run the test
*/
static void runTest( Class<? extends Service> testServiceClass )
{
try
{
// setup the services
Service testService =
testServiceClass.getConstructor( new Class<?>[] { String.class } )
.newInstance( "test service" );

FixedService fixedService = new FixedService( "fixed service" );

// start the services
testService.start();
fixedService.start();

// wait for testService to signal that it is done
System.out.println( "Started threads" );
while ( !testService.isDone() )
{
try
{
Thread.sleep( 1000 );
}
catch ( InterruptedException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// stop the fixed service
fixedService.stop();
System.out.println( "TestService done, fixed service told to shutdown" );
}
catch ( Exception e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/**
* I cannot modify this class. Handling of thread start is similar to real
* system.
*/
abstract static class Service implements Runnable
{
protected boolean isDone = false;
protected boolean stop = false;
private Thread thisServiceThread;

public Service( String name )
{
thisServiceThread = new Thread( this, name );
}

public boolean isDone()
{
return isDone;
}

public void start()
{
thisServiceThread.start();
}

public void stop()
{
this.stop = true;
}
}

/**
* I can modify this class. This is the class that actually runs my test.
*/
static class TestService extends Service
{
public TestService( String name )
{
super( name );
}

@Override
public void run()
{
System.out.println( "TestService: started" );

// TODO: How can I access FixedService.getMe from where without
// modifying FixedService?
try
{
Field field = FixedService.class.getDeclaredField( "getMe" );
field.setAccessible( true );
System.out.println( field.get( null ) );
}
catch ( SecurityException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch ( NoSuchFieldException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch ( IllegalArgumentException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch ( IllegalAccessException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println( "TestService: done" );
isDone = true;
}

}

/**
* I cannot modify this class. This is part of the system being tested.
*/
static class FixedService extends Service
{
private boolean getMe = false;

public FixedService( String name )
{
super( name );
}

@Override
public void run()
{
System.out.println( "FixedService: started" );

// don't stop until signaled to do so
while ( !stop )
{
try
{
Thread.sleep( 1000 );
}
catch ( InterruptedException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}

System.out.println( "FixedService: gotMe? " + getMe );

System.out.println( "FixedService: done" );
isDone = true;
}
}
}

最佳答案

正如 Hemal Pandya 所述,如果您想实际读取或操作该字段,您将需要服务对象,而不仅仅是类。

假设您需要的 Object 是在线程上设置的 Runnable,这是有可能的,需要一些非常肮脏的反射技巧。您必须使用私有(private)成员访问 hack 从线程中获取 target 字段,然后再次使用它来访问 runnable 本身所需的字段。

这是一些示例代码。请注意,我在这里并没有真正考虑线程同步问题(尽管我不确定是否有可能正确同步此类访问)

import java.lang.reflect.Field;

public class SSCCE {
static class T extends Thread {
private int i;

public T(int i) {
this.i = i;
}

@Override
public void run() {
while(true) {
System.out.println("T: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// ignore
}
}
}
}

static class R implements Runnable {
private int i;

public R(int i) {
this.i = i;
}

@Override
public void run() {
while(true) {
System.out.println("R: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// ignore
}
}
}
}

/**
* @param args
*/
public static void main(String[] args) {
Thread t1 = new T(1);
Thread t2 = new Thread(new R(2));

t1.start();
t2.start();

try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// ignore
}

setI(t1,3);
setI(t2,4);
}

static void setI(Thread t, int newVal) {
// Secret sauce here...
try {
Field fTarget = Thread.class.getDeclaredField("target");
fTarget.setAccessible(true);
Runnable r = (Runnable) fTarget.get(t);

// This handles the case that the service overrides the run() method
// in the thread instead of setting the target runnable
if (r == null) r = t;

Field fI = r.getClass().getDeclaredField("i");
fI.setAccessible(true);
fI.setInt(r, newVal);
} catch (Exception e) {
e.printStackTrace();
}
}

}

关于java - 跨线程反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7489247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com