日期:2014-05-20  浏览次数:20714 次

java中怎么在其他的类中获取一个返回类型为viod 的方法中的变量的值
我是java新手,遇到一个问题

public void serialEvent(SerialPortEvent event) {
String Weight = null;
try {
// 等待1秒钟让串口把数据全部接收后在处理
Thread.sleep(delayRead);
System.out.print("serialEvent[" + event.getEventType() + "]");
} catch (InterruptedException e) {
e.printStackTrace();
}
switch (event.getEventType()) {

case SerialPortEvent.DATA_AVAILABLE: // 1
try {
// 多次读取,将所有数据读入
// while (inputStream.available() > 0) {
// numBytes = inputStream.read(readBuffer);
// }
numBytes = inputStream.read(readBuffer);
//System.out.println("%%%%"+new String(readBuffer));
String weight = new String(readBuffer)
} catch (IOException e) {
e.printStackTrace();
Weight= null;
}
break;
}
}
就是如何在外面的类中读取到weight 的值,不能改变方法的返回类型void.

------解决方案--------------------
一般来说不可以,可以考虑用异常来达到目的,如:
class MyException extends Exception
{
public MyException(String message)
{
super(message);
}
}
class MyClass
{
public void doSomething()throws MyException
{
//do something
String mystr="mystr"
throw new MyException(mystr);
}
}
把你的方法改成类似的就行了.取值的时候只要用异常的getMessage方法就可以了.
------解决方案--------------------
讲Weight 作为一个public static String变量 在外部直接访问即可·