如何让Java方法返回多个值? [英] How can I have a Java method return multiple values?
问题描述
我只是想知道是否有办法让Java方法返回多个值。
I was just wondering whether there's a way to make a Java method return multiple values.
我正在创建一个使用jdbc库来处理a的应用程序数据库。我可以成功地将值输入到数据库中,但我需要一种方法来返回它们,这就是我有点卡住的地方。我创建了一个表单,用户输入一个特定的值(一个ID号),然后由执行我的数据库工作的Database类传递给它。
I'm creating an application that uses the jdbc library to work with a database. I can successfully enter values into the database but I need a way to return them, and this is where I'm a bit stuck. I creating a form into which the user enters a specific value (an ID number) which is then passed to by Database class which carries out my database work.
Database newQuery = new Database();
newQuery.getCust(c_ID); //uses the GetCust method in my class,
//passing it the ID of the customer.
我的Database类中的getCust()方法创建以下查询:
The getCust() method in my Database class creates the following query:
ResultSet Customer = stat.executeQuery("SELECT * FROM Persons WHERE Cust_ID=C_ID");
我需要一种方法来返回存储在客户中的结果。任何想法?
I need a way to return the results that are stored in Customer back. Any ideas?
推荐答案
您无法从Java中的方法中返回多个值,但始终可以返回容器对象它有几个值。在您的情况下,最简单的方法是返回ResultSet,Customer。
You can't exactly return multiple values from a method in Java, but you can always return a container object that holds several values. In your case, the easiest thing to do would be to return the ResultSet, Customer.
如果您担心将数据层暴露给UI,则可以复制将ResultSet中的数据转换为不太特定于数据库的结构,可以是List of Maps,也可以是Customer对象List,其中Custom是表示您的业务实体的新类。
If you're concerned about exposing your data layer to your UI, you can copy the data from the ResultSet into a structure that is less specific to the database, either a List of Maps, or perhaps a List of Customer objects, where Custom is a new class that represents your business entity.
这篇关于如何让Java方法返回多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!