java - 我想从类 2 访问类 1 的对象 **object** 来自另一个类让我们说类 3
问题描述
下面是声明为“客户端”的对象,我导入的另一个名为 mqttAndroidClient 的类
public class connection{
public void onCtreate(){
String clientId = MqttClient.generateClientId();
MqttAndroidClient client =
new MqttAndroidClient(getApplicationContext(), "tcp://" + TEXT + ":" + TEXT2,
clientId);
}
}
the object "client" of connection class, i wanna access it from a main class
public class main extends AppComptActivity{
//
//Attributes
//
public void onCreate(){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//onclick of button
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String topic = TOPIC;
String payload = PAYLOAD;
byte[] encodedPayload = new byte[0];
try {
encodedPayload = payload.getBytes("UTF-8");
MqttMessage message = new MqttMessage(encodedPayload);
message.setRetained(true);
client.publish(topic, message);
} catch (UnsupportedEncodingException | MqttException e) {
e.printStackTrace();
}
}
});
}
在上面的代码中,它无法将客户端识别为连接类中的对象
client.publish(topic, message);
i have tried to call it in main using
connection myobject = new connection(); myobject.onCreate();
but its throwing a declaration error i am very new to java and oops and
if the info is not efficient i will post the full code
解决方案
首先将 Connection 类中的客户端对象作为全局变量,并调用初始化对象的构造函数。
public class Connection {
MqttAndroidClient client;
Context context;
public Connection(Context context) {
this.context = context;
initClient(context);
}
public void initClient(Context context){
client =
new MqttAndroidClient(getApplicationContext(), "tcp://" + TEXT1 + ":" + TEXT2,
clientId);
}
public MqttAndroidClient getClient(){
return client;
}
}
现在在里面MainClass
首先获取对象,Connection class
然后通过调用返回客户端对象的方法从连接类中获取客户端对象。
主类内部
Connection connection= new Connection(this);
MqttAndroidClient client= connection.getClient();
推荐阅读
- php - Prestashop 模块未显示在列表中
- php - 如何使用此代码回显多行输入?
- c++ - 如何在 C++ 中将指针指定为“thread_local”存储?
- python - 我无法使用我的 jupyter notebook/jupyter lab,它是空白的
- ruby-on-rails - Ransacker:不支持的参数类型:字符串。改为构造一个 Arel 节点
- java - 使用 Hibernate 将 CSV 文件动态映射到数据库表
- sql - PowerPivot 导入中的 SQL 查询,使用单词“flag”作为列别名会破坏工作簿
- azure - Azure SQL 托管实例路由表
- protractor - 无法通过量角器关注 iframe 下的文本字段
- elasticsearch - 我的 MATCH 查询没有返回所有匹配的文档 Elastic