Instantiating Objects in Java - java

I asked a similar question to this recently, but I did a bad job at explaining it, so I am going to try again.
I cannot figure this out for the life of me. I have to do two different java files for this programming assignment, and when running the program from command prompt I get an error that says it cannot find symbol of when I create my object in the second class, and when I run the code in Eclipse I get the error "Error occurred during initialization of boot layer
java.lang.LayerInstantiationException: Package jdk.internal.jrtfs in both module jrt.fs and module java.base".
I even copied an example straight from the textbook to understand it, but it isn't working even though I have exactly what's in the textbook. The pastebin links are for the two classes that come from the textbook examples.
Please someone tell me what's wrong here.
First class: https://pastebin.com/KYHtDHPt
public class Account {
private String name;
public Account(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Second class: https://pastebin.com/ADUsjjaR
public class AccountTest {
public static void main(String[] args) {
Account account1 = new Account("Brandon Williams");
System.out.printf("Account one is: %s%n",account1.getName());
}
}

Related

Concept to create thread wide/class wide object

I'm searching for a concept to forward an object to subobjects.
Example:
I would like to create log files for several main Objects, that include sub objects (imagine a REST server that would log every single connection by ID).
Creating one big log file is simple ( redirect System.out.println, I already encapsulated that)
Example code:
class SubElementA{
public SubElementA(){
Debugger.debug("I am called, too");
}
}
Application.java
package com.dev4ag;
class Application{
private ElementA elA;
private String prefix;
public Application(String name){
this.elA = new ElementA();
this.prefix = name;
}
public void countUp(){
Debugger.debug(this.prefix+": I will now count up");
this.elA.doSomeStuff();
}
}
ElementA.java
package com.dev4ag;
class ElementA{
private int counter;
private SubElementA subElementA;
public void doSomeStuff(){
counter++;
Debugger.debug("Counter is: "+counter);
}
//Constructor
public ElementA(){
subElementA = new SubElementA();
this.counter = 0;
};
}
SubElementA.java
package com.dev4ag;
class SubElementA{
public SubElementA(){
Debugger.debug("I am called, too");
}
}
Debugger.java
package com.dev4ag;
public class Debugger {
public static void debug(String output){
//Just imagine we would write to a file here ;)
System.out.println(output);
}
}
(it was more easy to write system.out.println than to create a file, just imagine, Debugger.debug would write to a file).
Now I am thinking about a solution to create one Debug output target for each App. I could definitely change debug to not being static and create a debug object within Application.
But is there any way to use this object in the sub classes without forwarding the debug object either through Constructor or setter function, which would mean to have to add an object for the debugger to each class?
What would be the most beautiful solution for that?
Note that this solution might decrease performance a lot and it is pretty dirty way, but some loggers include such data.
But you can use Thread.currentThread().getStackTrace() to get stacktrace like in error and get class and method from where your method was called.
If you are using java9+ then you should probably use StackWalker API instead, especially that it have nice filters and other useful features.
So then you could guess app by class/method names on the stack.

Static variable set, but not gettable - Class loading issue ( possibly?)

This is very strange to me:
1) I have a class
public class Data {
private static String name;
public static String getName() {
return name;
}
public static void setName (String n){
Data.name = n;
}
}
this class variable name is set correctly during my server ( J2EE app in WAS liberty) startup - I wanted to cache this data during the whole server lifecycle.
2) but when I hit an URL that eventually invokes a code that does a getter:
Data.getName(); // this returns null??
Can anyone think of a possible reason? Not be able to debug also, I am very frustrated.
To illustrate my problem more, let me show my project structure:
EAR
CommonJar
WAR1 WAR2
My Data.java is in CommonJar. This Data.java is initialized in WAR1 during the server startup triggered by a Listener registered in web.xml, and from here I saw it is set and I saw the non-null value using Data.getName().-- this is my step 1 in my original post.
Then I have a restful HelloWorld Service in WAR2. And when I call into this HelloWorld service, I see Data.getName() returns null. -- this is my step 2 in my original post. Don't even think anything like syntax type of easy error, because it is not that.
My theory is: it seems that Data.java is loaded by classloader in WAR1 in step 1 and then WAR 2 in my step 2, and Step 2 loaded an empty Data class.
To verify if this theory is correct, I moved Data.java initialization step into the WAR2, (and again I saw it is set and I saw the non-null value using Data.getName()), the difference is that when I call into this HelloWorld service, I saw Data.getName() returns the expected non-null value. This step is what I call my troubleshooting breakthrough because it seems to indicate my theory was correct. (but I can't fix the issue by moving the code in my real problem fix)
Then the question is how to fix and how to visually see which class is loaded by which class loader and when? Also based on WAS Liberty doc, the default class loader will be parentsfirst, which means Data.java should be loaded by the parent ( in this case, EAR), so I shouldn't have my problem the first place.
Anyone, please guide how to further to see the problem and fix it? Thanks.
Your getName() function is declared with no return type, yet attempts to return a string.
try out this one
public class Data {
public static void main(String... args) {
System.out.println("setting name 'Stack Overflow'");
Data.setName("Stack Overflow");
System.out.println("now getting the setted name");
System.out.println(Data.getName());
}
private static String name;
public static String getName() {
return name;
}
public static void setName(String n) {
Data.name = n;
}
}
Output:
setting name 'Stack Overflow'
now getting the setted name
Stack Overflow
In your code, you defined no return types to your methods.

java: using an array of objects across files

OK so, im very new to java and the solution is probably simple so please bear with me, but basically i'm trying to make a film database using an array of a movie class. i have 3 .java files: the tester, the database, and the movie class. my problem is i'm really not sure how to make my tester file recognize the movies array from the database file, and every solution ive found has just given me more errors.
tester:
public class DatabaseTester extends MovieDatabase{
public static void main(String[] args) {
System.out.println(MovieDatabase.movies[1].getTitle());
}
}
the database:
public class MovieDatabase {
public static Movie movies[] = new Movie[2];
public static void movieDb(String[]args){
movies[1].setTitle("Test Title");
}
}
^the movie class has a set title method. i'm not too sure about the database's code in particular but it was the only way i could find that didn't give me errors. i'll post the full movie class if necessary but it's quite long so... only if needed
the error i get if i try to getTitle(); from the MovieDatabase:
Exception in thread "main" java.lang.NullPointerException
at DatabaseTester.main(DatabaseTester.java:35)
i'm aware this error is from the program thinking the array is not initialized, so it just must not be recognizing my database file... if i try to getTitle from the MovieDatabase, it simply doesn't recognize it, and will either give me an error or nothing. i cannot find a way to get around this aside from putting the Movie initialization in the main (which i have confirmed works, but it's not what i want to do).
You can try this the following changed code In the class DatabaseTester
public class DatabaseTester {
public static void main(String[] args) {
System.out.println(Database.movies[0].getTitle());
}
}

Error: Main method not found in class... why am I getting this?

Before people start flagging this question as a duplicate, know that I took the time too look at similar questions, and found that the answers to other "Error: Main method not found in class..." were not clearly applicable to my situation (according to my limited understanding of java)
I'm trying to utilize a text to speech api. Eclipse isn't complaining about the following code until I try to compile:
package com.textToSpeech;
import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;
public class FreeTTS {
private static final String VOICENAME_kevin = "kevin";
private String text; // string to speech
public FreeTTS(String text) {
this.text = text;
}
public void speak() {
Voice voice;
VoiceManager voiceManager = VoiceManager.getInstance();
voice = voiceManager.getVoice(VOICENAME_kevin);
voice.allocate();
voice.speak(text);
}
public static void main(String[] args) {
String text = "FreeTTS was written by the Sun Microsystems Laboratories "
+ "Speech Team and is based on CMU's Flite engine.";
FreeTTS freeTTS = new FreeTTS(text);
freeTTS.speak();
}
}
The following error shows up in the console:
Error: Main method not found in class com.textToSpeech.FreeTTS, please define the main method as:
public static void main(String[] args)
The code above obviously has a main method, so does anyone know why I am getting this error, and furthermore how I can fix it?
I think it has something to do with the name of the class. If I change the name of the class to something like t2s and then try to compile, I get this error:
Error: Could not find or load main class com.textToSpeech.t2s
Anybody have any thoughts? Any help would be really appreciated.
You may have messed up your project properties. I don't use eclipse, so I cannot say for sure, but try creating a new project and adding the same code to it without fiddling with the properties. The class name and the file name should be the same, check that. Also make sure that the source file is in the same package folder. If nothing works, just create a new project.
Cheers.

Problems passing class objects through GWT RPC

I've run through the Google Web Toolkit StockWatcher Tutorial using Eclipse and the Google Plugin, and I'm attempting to make some basic changes to it so I can better understand the RPC framework.
I've modified the "getStocks" method on the StockServiceImpl server-side class so that it returns an array of Stock objects instead of String objects. The application compiles perfectly, but the Google Web Toolkit is returning the following error:
"No source code is available for type com.google.gwt.sample.stockwatcher.server.Stock; did you forget to inherit a required module?"
It seems that the client-side classes can't find an implementation of the Stock object, even though the class has been imported. For reference, here is a screenshot of my package hierarchy:
I suspect that I'm missing something in web.xml, but I have no idea what it is. Can anyone point me in the right direction?
EDIT: Forgot to mention that the Stock class is persistable, so it needs to stay on the server-side.
After much trial and error, I managed to find a way to do this. It might not be the best way, but it works. Hopefully this post can save someone else a lot of time and effort.
These instructions assume that you have completed both the basic StockWatcher tutorial and the Google App Engine StockWatcher modifications.
Create a Client-Side Implementation of the Stock Class
There are a couple of things to keep in mind about GWT:
Server-side classes can import client-side classes, but not vice-versa (usually).
The client-side can't import any Google App Engine libraries (i.e. com.google.appengine.api.users.User)
Due to both items above, the client can never implement the Stock class that we created in com.google.gwt.sample.stockwatcher.server. Instead, we'll create a new client-side Stock class called StockClient.
StockClient.java:
package com.google.gwt.sample.stockwatcher.client;
import java.io.Serializable;
import java.util.Date;
public class StockClient implements Serializable {
private Long id;
private String symbol;
private Date createDate;
public StockClient() {
this.createDate = new Date();
}
public StockClient(String symbol) {
this.symbol = symbol;
this.createDate = new Date();
}
public StockClient(Long id, String symbol, Date createDate) {
this();
this.id = id;
this.symbol = symbol;
this.createDate = createDate;
}
public Long getId() {
return this.id;
}
public String getSymbol() {
return this.symbol;
}
public Date getCreateDate() {
return this.createDate;
}
public void setId(Long id) {
this.id = id;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
}
Modify Client Classes to Use StockClient[] instead of String[]
Now we make some simple modifications to the client classes so that they know that the RPC call returns StockClient[] instead of String[].
StockService.java:
package com.google.gwt.sample.stockwatcher.client;
import com.google.gwt.sample.stockwatcher.client.NotLoggedInException;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
#RemoteServiceRelativePath("stock")
public interface StockService extends RemoteService {
public Long addStock(String symbol) throws NotLoggedInException;
public void removeStock(String symbol) throws NotLoggedInException;
public StockClient[] getStocks() throws NotLoggedInException;
}
StockServiceAsync.java:
package com.google.gwt.sample.stockwatcher.client;
import com.google.gwt.sample.stockwatcher.client.StockClient;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface StockServiceAsync {
public void addStock(String symbol, AsyncCallback<Long> async);
public void removeStock(String symbol, AsyncCallback<Void> async);
public void getStocks(AsyncCallback<StockClient[]> async);
}
StockWatcher.java:
Add one import:
import com.google.gwt.sample.stockwatcher.client.StockClient;
All other code stays the same, except addStock, loadStocks, and displayStocks:
private void loadStocks() {
stockService = GWT.create(StockService.class);
stockService.getStocks(new AsyncCallback<String[]>() {
public void onFailure(Throwable error) {
handleError(error);
}
public void onSuccess(String[] symbols) {
displayStocks(symbols);
}
});
}
private void displayStocks(String[] symbols) {
for (String symbol : symbols) {
displayStock(symbol);
}
}
private void addStock() {
final String symbol = newSymbolTextBox.getText().toUpperCase().trim();
newSymbolTextBox.setFocus(true);
// Stock code must be between 1 and 10 chars that are numbers, letters,
// or dots.
if (!symbol.matches("^[0-9a-zA-Z\\.]{1,10}$")) {
Window.alert("'" + symbol + "' is not a valid symbol.");
newSymbolTextBox.selectAll();
return;
}
newSymbolTextBox.setText("");
// Don't add the stock if it's already in the table.
if (stocks.contains(symbol))
return;
addStock(new StockClient(symbol));
}
private void addStock(final StockClient stock) {
stockService.addStock(stock.getSymbol(), new AsyncCallback<Long>() {
public void onFailure(Throwable error) {
handleError(error);
}
public void onSuccess(Long id) {
stock.setId(id);
displayStock(stock.getSymbol());
}
});
}
Modify the StockServiceImpl Class to Return StockClient[]
Finally, we modify the getStocks method of the StockServiceImpl class so that it translates the server-side Stock classes into client-side StockClient classes before returning the array.
StockServiceImpl.java
import com.google.gwt.sample.stockwatcher.client.StockClient;
We need to change the addStock method slightly so that the generated ID is returned:
public Long addStock(String symbol) throws NotLoggedInException {
Stock stock = new Stock(getUser(), symbol);
checkLoggedIn();
PersistenceManager pm = getPersistenceManager();
try {
pm.makePersistent(stock);
} finally {
pm.close();
}
return stock.getId();
}
All other methods stay the same, except getStocks:
public StockClient[] getStocks() throws NotLoggedInException {
checkLoggedIn();
PersistenceManager pm = getPersistenceManager();
List<StockClient> stockclients = new ArrayList<StockClient>();
try {
Query q = pm.newQuery(Stock.class, "user == u");
q.declareParameters("com.google.appengine.api.users.User u");
q.setOrdering("createDate");
List<Stock> stocks = (List<Stock>) q.execute(getUser());
for (Stock stock : stocks)
{
stockclients.add(new StockClient(stock.getId(), stock.getSymbol(), stock.getCreateDate()));
}
} finally {
pm.close();
}
return (StockClient[]) stockclients.toArray(new StockClient[0]);
}
Summary
The code above works perfectly for me when deployed to Google App Engine, but triggers an error in Google Web Toolkit Hosted Mode:
SEVERE: [1244408678890000] javax.servlet.ServletContext log: Exception while dispatching incoming RPC call
com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract com.google.gwt.sample.stockwatcher.client.StockClient[] com.google.gwt.sample.stockwatcher.client.StockService.getStocks() throws com.google.gwt.sample.stockwatcher.client.NotLoggedInException' threw an unexpected exception: java.lang.NullPointerException: Name is null
Let me know if you encounter the same problem or not. The fact that it works in Google App Engine seems to indicate a bug in Hosted Mode.
GWT needs the .java file in addition to the .class file. Additionally, Stock needs to be in the "client" location of a GWT module.
The GWT compiler doesn't know about Stock, because it's not in a location it looks in. You can either move it to the client folder, or if it makes more sense leave it where it is and create a ModuleName.gwt.xml that references any other classes you want, and get your Main.gwt.xml file to inherit from that.
eg: DomainGwt.gwt.xml
<module>
<inherits name='com.google.gwt.user.User'/>
<source path="javapackagesabovethispackagegohere"/>
</module>
and:
<module rename-to="gwt_ui">
<inherits name="com.google.gwt.user.User"/>
<inherits name="au.com.groundhog.groundpics.DomainGwt"/>
<entry-point class="au.com.groundhog.groundpics.gwt.client.GPicsUIEntryPoint"/>
</module>
There's a better answer here: GWT Simple RPC use case problem : Code included
Basically, you can add parameters to your APPNAME.gwt.xml file so the compiler to give the compiler a path to the server-side class.
I was getting the same issue and the "mvn gwt:compile" output was not very helpful.
Instead, when I tried deploying to tomcat (via the maven tomcat plugin: mvn tomcat:deploy) I got helpful error messages.
A few things I had to fix up:
Make the object that is sent from the client to the server implement Serializable
Add an empty-arg constructor to that same object
Yes, it is sure that we need to use the Serialization for getting the server objects to the client. These modile?? file settings won't work to use the Stock class in the client side.
In your case you have only one class Stock and you can create a StockClient in client side. It is easy. But what will be the solution if anyone having more classes. Something like the properties of this class are also some other type of classes.
Example: stock.getEOD(date).getHigh();
getEOD will return another class with the given date and that class has the getHigh method.
What to do in such big cases? I don't think creating all classes implementing serialization in client side is good for that. Then we have to write code in both server and client. all classes two times.
Keying off of rustyshelf's answer above ...
In my case I needed to edit the ModuleName.gwt.xml file and add the following:
<source path='client'/>
<source path='shared'/>
I created my project with the New->Web Application Project wizard but unchecked the Generate project sample code option. I then created the shared package. Had I not unchecked that, the package would have been created for me and the xml file modified per the above.
There is a far more simple and easy solution for that. If you want to send an object of your custom designed class from server side to client side you should define this custom class in shared package.
For example for your case the you just have to carry the Stock.java class (by drag and drop) into
com.google.gwt.sample.stockwatcher.shared
package. However from your package hierarchy screenshot it seems that you had deleted this shared package. Just re-create this package and drop the Stock.java inside it and let the game begin.

Categories