gpt4 book ai didi

java - 我可以使用不同类的静态方法吗?

转载 作者:行者123 更新时间:2023-11-30 04:01:23 24 4
gpt4 key购买 nike

下面是我的 CuratorClient 类,它连接到 Zookeeper 并启动领导者选举过程。

public class CuratorClient {

// can I make this as static?
private static CuratorFramework client;
private String latchPath;
private String id;
private LeaderLatch leaderLatch;

public CuratorClient(String connString, String latchPath, String id) {
client = CuratorFrameworkFactory.newClient(connString, new ExponentialBackoffRetry(1000, Integer.MAX_VALUE));
this.id = id;
this.latchPath = latchPath;
}

public void start() throws Exception {
client.start();
client.getCuratorClient().blockUntilConnectedOrTimedOut();
leaderLatch = new LeaderLatch(client, latchPath, id);
leaderLatch.start();
}

public boolean isLeader() {
return leaderLatch.hasLeadership();
}

public Participant currentLeader() throws Exception {
return leaderLatch.getLeader();
}

public void close() throws IOException {
leaderLatch.close();
client.close();
}

// can I use below method from any other class ?
protected static List<String> getChildren(String node) throws Exception {
return client.getChildren().forPath(node);
}
}

当我的服务启动时,在静态 block 中,我将使用 CuratorClient 连接到 Zookeeper,并启动领导者选举过程。

public class TestService {

private static CuratorClient curatorClient = null;
static {

try {
String connectionString = "some-string";
String hostname = "machineA";

curatorClient = new CuratorClient(connectionString, "/my/latch", hostname);
curatorClient.start();

} catch (Exception ex) {
// log exception
}
}

....
....

// some method
public Map<String, String> installNewSoftware(String node) {

//.. some other code
try {
List<String> children = CuratorClient.getChildren("/my/example");
System.out.println(children);

} catch (Exception e) {
e.printStackTrace();
}

//.. some other code
return null;
}
}

现在我还有一些其他类喜欢使用CuratorClientgetChildren方法,所以在这个类中,我可以像这样直接使用CuratorClient。 getChildren("/my/example"); 正确吗?

public class DifferentClass {

....
....

// some new method
public Map<String, String> installNewSoftware(String node) {
try {
List<String> children = CuratorClient.getChildren("/my/example");
System.out.println(children);

} catch (Exception e) {
e.printStackTrace();
}

//.. some other code
return null;
}
}

总的来说,这不是馆长问题或动物园管理员问题。这基本上是一个设计问题,我想了解我这样做的方式是否会有任何问题?我假设 CuratorFramework 也将是线程安全的?

最佳答案

是的,您可以从其他类调用静态方法。

您的签名如下所示:

protected static List<String> getChildren(String node) throws Exception

您无法从另一个类调用它的原因是它是 protected (对当前类和子类可见)而不是公共(public)的(对任何地方都可见)。

如果使其可见,则可以使用 CuratorClient.getChildren() 调用它。

More information on access modifiers .
More information on class members (static fields) .

关于java - 我可以使用不同类的静态方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21917917/

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