简体   繁体   English

Java类成员变量

[英]Java Class member variable

I'm developing a research framework that needs to allow users to override core functionality. 我正在开发一个研究框架,该框架需要允许用户覆盖核心功能。

I have a core class, called TorSocket, that has a method called createCircuit() which returns a TorCircuit class. 我有一个名为TorSocket的核心类,它具有一个名为createCircuit()的方法,该方法返回一个TorCircuit类。 I want users of the framework to be able to override TorCircuit functions without modifying the source but because the only way to create such a class is through TorSocket.createCircuit() I'm not sure how to. 我希望框架的用户能够在不修改源代码的情况下覆盖TorCircuit函数,但是因为创建此类的唯一方法是通过TorSocket.createCircuit()所以我不确定该怎么做。

I've tried as follows, in TorSocket, creating a member variable: 我已经尝试在TorSocket中创建成员变量,如下所示:

 public Class circuitClass;

and then users could do: 然后用户可以执行以下操作:

 sock.circuitClass = class MyCircuitClass extends TorCircuit { ...

and the TorSocket class would use circuitClass to instantiate. 并且TorSocket类将使用circuitClass进行实例化。

However, I'm getting a syntax error using the above code, at "class." 但是,在“类”中,使用上述代码遇到语法错误。 What is the correct syntax for this? 正确的语法是什么? I cant find much online although welcome pointers. 尽管欢迎指点,但我在网上找不到太多内容。

Finally, how to I then use TorSocket.circuitClass to instantiate? 最后,我该如何使用TorSocket.circuitClass实例化?

Many thanks Gareth 非常感谢Gareth

Use 采用

class MyCircuitClass extends TorCircuit {...}
sock.circuitClass = MyCircuitClass.class;

您不能让用户扩展您的基类,但仍然想自己控制对象的创建(您将如何精确地执行此操作?用户可以简单地调用new MyCircuitClass() )-如果您想将对象的创建集中在内部我建议创建一个基类正在使用的接口集,用户必须提供具体的实现以通过工厂创建对象。

It seems a better way to do this is to use Generic methods like so: 似乎更好的方法是使用通用方法,如下所示:

public <T extends TorCircuit> T createCircuit(Class<T> torCircClass, boolean blocking) {
    T circ;
    try {
        circ = torCircClass.getDeclaredConstructor(TorSocket.class).newInstance(this);
    } catch (InstantiationException  | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
        throw new RuntimeException(e);
    }
    circ. ...
    return circ;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM