I want to call a string, in client.java, from the main class of server.java file but miserably failing...
Any help would be appreciated
Please make an example so my stupid brain can understand it...
package whatever.user.locahost.server;
public class Server {
public static void main(String[] args) {
//
int portNumber = 666;
boolean socketActive = false;
public static String serverDomain = "DOMAIN NAME";
}
}
//In client.java main class
...
ServerDomainGetter serverDomain = new ServerServerDomainGetter(serverDomain);
String serverDomainGetter = serverDomain;
String clientDomain = "ClientDomain.uk"; //TODO read from file
String clientUserName = "Demo";
...
So the client.java class cannot access a non static class level variable from server.java the way you are trying to access it. Also can't use the final modifier if you want to make it static.
public static String serverDomain = "DOMAIN NAME"
If you instantiate the variable like that in the server.java class then you will be able to access it the way you are trying to access it.
More information on statics:
https://codegym.cc/groups/posts/141-10-things-you-need-to-know-about-the-static-modifier-in-java
Declaring public static String serverDomain = "domain.uk" should be outside the main. Posting the final code below. HUGE thanks to #isaace
public class Server {
public static String serverDomain = "domain.uk";
public static void main(String[] args) {
int portNumber = 666;
String serverDomain = "domain.uk";
System.out.println(serverDomain);
}}
public class Client {
public static void main(String[] args) {
System.out.println("Server domain: " + Server.serverDomain);
String clientDomain = "ClientDomain.uk ";
String clientUserString = "Demo";
System.out.println("Client Domain: "+ clientDomain + " clientUser: "+clientUserString);
}}
Related
I have a class named PointOfSale which have a public method getTpid, but I failed when I want to call this method in my main class, I can only call "TPID_FIELD_NUMBER", how to solve this problem?
PointOfSale ps = new PointOfSale();
ps.TPID_FIELD_NUMBER; //correct
ps.getTpid();// error
public final class PointOfSale implements PointOfSaleOrBuilder {
public static final int TPID_FIELD_NUMBER = 1;
private int tpid_;
#java.lang.Override
public int getTpid() {
return tpid_;
}
}
public interface PointOfSaleOrBuilder {
int getTpid();
}
I think that you just need to add () at the end of your call.
ps.TPID_FIELD_NUMBER is a call for a constant.
If you want to call a method, you should call like this: ps.getTpid();
public static void main(String[] args) {
PointOfSale ps = new PointOfSale();
ps.getTpid();
}
The issue is with the line "ps.TPID_FIELD_NUMBER;". This will give "Not a statement" error. You should assign it to a variable for successful execution.
Your code should look like,
public static void main(String[] args) {
PointOfSale ps = new PointOfSale();
int num = ps.TPID_FIELD_NUMBER;
ps.getTpid();
}
New to java, and I'm currently relying on lots of output messages to trace activity. I'd like a way to do this cleanly, to make 'semi-redundant' code as inconspicuous as possible.
Originally, I was doing this: (Note the System.out.println statements.)
package hamburger;
...
public class Hamburger extends Application {
...
public static void main(String args[]){
System.out.println("---> hamburger.Hamburger.main");
...
String [] drink = {"pepsi"};
NoCoke.onlypepsi(drink);
... ...
public class NoCoke
public static void main(String args[]){
System.out.println("---> hamburger.NoCoke.main");
...
static void justpepsi(String... commandIn){
System.out.println("---> hamburger.NoCoke.justpepsi");
...
try{ to get coke anyway...
Of course, when I moved things around or renamed stuff, all these literals had to be updated, so I started doing things dynamically using these three lines:
public class Hamburger
public static void main(String[] args) {
String nameClass = new Throwable().getStackTrace()[0].getClassName();
String nameMethod = new Throwable().getStackTrace()[0].getMethodName();
System.out.println("---> "+nameClass+"."+nameMethod);
public class NoCoke
public static void main(String args[]){
<AND HERE>
public static void justpepsi(String... commandIn){
<AND HERE>
It works fine:
---> hamburger.Hamburger.main
---> hamburger.NoCoke.main
---> hamburger.NoCoke.justpepsi
But I hate the way it looks, takes up space, etc.
Is there anything like a 'copy-book' in java? - a doc that contains executable code that can be dropped anywhere? Or is there a procedure to define the code as something like 'a String' that could be declared in the constructor, something like this:
StringThing nameMessageRoutine = new (whatever...) StringThing
"String nameClass = new Throwable()...<etc>...
System.out.println('---> '+nameClass+'.'+nameMethod);'"
...that I could just 'import' or 'refer to' like this:
public class Hamburger extends Application {
public static void main(String args[]){
import: nameMessageRoutine; //outside of the package member
public class NoCoke
public static void main(String args[]){
reference: nameMessageRoutine; //defined in the constructor
This method prints information about from where it was called:
static void printCurrent() {
final StackTraceElement ste = new Throwable().getStackTrace()[1];
String methodName = ste.getMethodName();
String className = ste.getClassName();
String lineNum = ""+ste.getLineNumber();
System.out.println(className + ", " + methodName + ", Line " + lineNum);
}
For example:
package randomTest;
public class MainClass {
public static void main(String[] args) {
printCurrent();
}
}
The output is
randomTest.MainClass, main, Line 131
EDIT:
I know this doesn't exactly answer the question, but it does accomplish the final goal of tracing code activity. To answer the question (as per the title), there is no way in pure Java to automatically insert routines into marked places.
My aim was to create a little bit of code which allows my computer to randomly select how it refers to me. "Hello " + (randomly selected nickname) + ", how are you today?"
Pretty simple, right? Not to a noob like me!
Referenced Class
I gave it 4 choices of names, and it selects one at random and prints it out.
public class NameRef {
public static void main(String[] args){
ArrayList<String> nickNames = new ArrayList<String>();
nickNames.add("DJ");
nickNames.add("Buddy");
nickNames.add("Dude");
nickNames.add("Sir");
Random rand = new Random();
rand.nextInt(4);
System.out.println(nickNames.get(rand.nextInt(4)));
}
}
Main Class
I wanted this class to take the information from that secondary class' function and reference to it in my greeting.
public class CodeTesting extends NameRef {
public static void main(String[] args) {
System.out.println("Hello, " + /*The product from the NameRef*/ + " how are you?");
}
}
I don't know how I am supposed to reference that information? I've tried is a hundred ways!
I also tried to make a function in the secondary class that RETURNED a name string but then I wasn't able to reference that in my main class...
I am so confused. Any help as to where I'm going wrong would be great. Thanks.
Change main in NameRef to a function that returns String. So instead of System.out.println(nickNames.get(rand.nextInt(4)));, it should instead do return nickNames.get(rand.nextInt(4)). Then in CodeTesting class, call the function like this:
public class CodeTesting extends NameRef {
public static void main(String[] args) {
System.out.println("Hello, " + nameOfFunction() + " how are you?");
}
}
Where nameOfFunction is the name you call the function you created
public class NameRef {
public String getName(){
ArrayList<String> nickNames = new ArrayList<String>();
nickNames.add("DJ");
nickNames.add("Buddy");
nickNames.add("Dude");
nickNames.add("Sir");
Random rand = new Random();
rand.nextInt(4);
return nickNames.get(rand.nextInt(4));
}
}
public class CodeTesting extends NameRef {
public static void main(String[] args) {
NameRef nameRefObject = new NameRef();
System.out.println("Hello, " +nameRefObject.getName()+ " how are you?");
}
}
I want to generate custom getters and setter, so I can handle variables better when I will be saving these instances into SQL database. I want to generate something like:
public class Test extends SQLEntry {
private static final String NAME = "Name";
public String getName() {
return get(NAME);
}
public void setName(String name) {
set(NAME, name);
}
}
But as I can see in Eclipse it generates only the following code:
public class Test {
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
Is there some plugin, that can do it? Or am I missing something?
I have like 20 classes and I will not write this manually.
I dont know why you need this, but here is the approach to custom Getters and Setters.
You can update all generated setters and getters by going to preferences > java > Code Style > code Templates and selecting code then edit Getter body and Setter body and put this:
Getter body: return get(${field});
Setter body: set(${field}, ${param});
Let me know if that works
I recommend that instead of doing what you describe, you should use Spring Data. Specifically the BeanPropertyRowMapper class in the org.springframework.jdbc.core package will do what you want.
Read more in the Spring API documentation.
there is no other plugin available!
how can some plugin write code that is specific to your business logic!
you have to write the code manually for setters and getters in all the classes!
Try write-it-once. Template based code generator. You write custom template using Groovy, and generate file depending on java reflections. It's the simplest way to generate any file. You can make getters/settest/toString by generating AspectJ or java files, SQL based on JPA annotations, inserts / updates based on enums and so on.
On the end I found it that it is the best to do it your self...
If you like writing a code than you will enjoy this solution the most.
public class CodeGenerator {
private final static String ENCODING = "UTF-8";
private final static String FILE_NAME = "File.txt";
public static void main(String[] args) {
try {
ArrayList<Carriage> names = getNames();
for (Carriage c : names) {
createSetter(c.name, c.capitalName);
createGetter(c.name, c.capitalName);
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
private static ArrayList<Carriage> getNames() throws FileNotFoundException {
File file = new File("/");
InputStream is = CodeGenerator.class.getResourceAsStream(FILE_NAME);
Scanner s = new java.util.Scanner(is, ENCODING).useDelimiter("\\A");
String content = s.next();
String[] lines = content.split(System.getProperty("line.separator"));
ArrayList<Carriage> ret = new ArrayList<Carriage>();
for (String line : lines) {
line = line.replaceAll("\\r", "");
int firstCapitalIndex = line.indexOf("String") + 7;
int secondCapitalIndex = line.indexOf(" ", firstCapitalIndex);
int firstIndex = line.indexOf("\"") + 1;
int secondIndex = line.indexOf("\"", firstIndex + 1);
Carriage c = new Carriage();
c.name = line.substring(firstIndex, secondIndex);
c.capitalName = line.substring(firstCapitalIndex, secondCapitalIndex);
ret.add(c);
}
return ret;
}
public static void createSetter(String name, String capitalName) {
String str = "public void set" + name + "(String val) {\n"
+ "\tset(" + capitalName + ", val);\n"
+ "}\n";
System.out.println(str);
}
public static void createGetter(String name, String capitalName) {
String str = "public String get" + name + "() {\n"
+ "\treturn (String) get(" + capitalName + ");\n"
+ "}\n";
System.out.println(str);
}
carriage:
package codegenerator;
public class Carriage {
public String name;
public String capitalName;
}
And to File.txt I just coppy all defined constants and run the generator...
public static final String NAME = "Name";
public static final String PHONE = "Phone";
public static final String EMAIL = "Email";
public static final String ADDRESS_1 = "Address1";
public static final String ADDRESS_2 = "Address2";
public static final String ADDRESS_3 = "Address3";
public static final String ICO = "Ico";
public static final String DIC = "Dic";
public static final String ADMIN_LOGIN = "AdminLogin";
public static final String ADMIN_PASSWORD = "AdminPassword";
public static final String LANGUAGE = "Language";
public static final String CODE = "CODE";
public static final String MONTHLY_PAYMENT = "MonthlyPayment";
Not sure if the title makes sense, but I am trying to return a Success message from a class that receives a linkedhashmap, however eclipse is giving me error when I try to compile the files, offering
Remove arguments to match 'logFile()'
Create constructor 'logFile(Map<String, String>)'
How do set it up to send a Map and revieve a String?
thx
Art
Code corrected as per #Jeff Storey below with error suppression for eclipse
calling class
eventLog.put(stringA,stringB);
logFile logStuff = new logFile();
successRtn = logFile.Process(eventLog);
// Do Stuff with SuccessRtn
logFile class
public class logFile {
static String Success = "Fail";
public static String Process(Map<String, String> eventlog){
// Do Stuff
Success = "Yeh!"
return Success;
}
public static void main(String[] args){
#SuppressWarnings("static-access")
String result = new logFile().Procces(eventLog);
System.out.println("result = " + result);
}
The main method is a special method whose signature must public static void main(String[] args) when being used as an entry point to your application. Create a second method that does the actual work, like this:
public class LogFile {
public String process(Map<String,String> eventLog) {
// do stuff
return success;
}
public void main(String[] args) {
// eventLog will probably be read from a filepath passed into the args
String result = new LogFile().process(eventLog);
System.out.println("result = " + result);
}
}
Note that a lot of your naming conventions are also non standard. Classes should begin with a capital letter and variables should begin with a lower case.