简体   繁体   中英

use a constructor as a method parameter

I'm writing a class that will build a SQL table create statement. what I'd like to do is call a method something like createTable(String tableName ColAndTypes... ct ) . When I write the method I don't get any compile errors. I'm having trouble passing the values into the method when I call it though and I think it's because my syntax is wrong and I'm not sure how to fix it. I was wondering if you could look at the example I have provided and let me know what I need to do to fix it. Thanks so much for your help!

import java.util.*;
public class foo
{
public class bar{
    public String sBar1, sBar2;
    public bar(){
        sBar1 = "null";
        sBar2 = "null";
    }
    public bar(String sBar1, String sBar2){
    this.sBar1 = sBar1;
    this.sBar2 = sBar2;
    }
}

String sFoo;
List<bar> bi;

public foo(){
    sFoo = "null";
    bi = new bar();
}
public foo(Strinf sFoo, bar bi){
    this.sFoo = sFoo;
    this.bi = bi;
}

public void runFooBar(String sFoo, bar... barArgs)
{
    this.sFoo = sFoo;
    for(bar x:barArgs){System.out.Println(bi.get(x).sBar1   + ":" + bi.get(x).sBar2);}
}

public static void main(String[] args)  
{
    foo fi = new foo();
    fi.runFooBar("foo 1", ("1 sBar1","1 sBar2"),("2 sBar1 ","2 sBar2"))

}//end main

}//end class

I'm not entirely sure what you're trying to do, but this fixes your syntax errors.

import java.util.ArrayList;
import java.util.List;

public class Foo {
    public static class Bar {
        public String sBar1, sBar2;

        public Bar(String sBar1, String sBar2) {
            this.sBar1 = sBar1;
            this.sBar2 = sBar2;
        }
    }

    String sFoo;
    List<Bar> bi;

    public Foo() {
        bi = new ArrayList<>();
    }

    public Foo(String sFoo, List<Bar> bi) {
        this.sFoo = sFoo;
        this.bi = bi;
    }

    public final void runFooBar(String sFoo, Bar... barArgs) {
        this.sFoo = sFoo;
        for (Bar x : barArgs) {
            System.out.println(x.sBar1 + ":" + x.sBar2);
        }
    }

    public static void main(String[] args) {
        Foo fi = new Foo();
        fi.runFooBar("foo 1", new Bar("1 sBar1", "1 sBar2"), new Bar("2 sBar1", "2 sBar2"));

    }//end main
}//end class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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