This is my code.
private void btnloginActionPerformed(java.awt.event.ActionEvent evt) {
String username = "";
String sql = "select * from userinfo where uname=? and pword=?";
try{
pst = conn.prepareStatement(sql);
pst.setString(1, txt_username.getText());
pst.setString(2, txt_password.getText());
rs=pst.executeQuery();
if(rs.next()){
afterLogin pwcorrect = new afterLogin();
pwcorrect.setVisible(true);
this.setVisible(false);
username = txt_username.getText();
}
else{
JOptionPane.showMessageDialog(null, "Username and Password are Incorrect.");
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
I need to access the value of username from another class. Is there any way for this??? Please help me with code.
That's not just defined in the class, it's defined in a method in a class.
This isn't a "private" variable (or class), it's an invisible variable as far as other classes are concerned. Expose it with a public getter, or provide a mechanism the code can set it on something else.
Since this is an action handler you also need to make sure the variable will only be accessed after it's been set, or that however it's accessed can deal with it not having a value.
public class WhateverClassThisIs {
private String username;
public String getUsername() { return username; }
private void btnloginActionPerformed(java.awt.event.ActionEvent evt) {
String sql = "select * from userinfo where uname=? and pword=?";
try {
// As before, but:
if (rs.next()) {
username = txt_username.getText();
}
}
}
}
public class SomeOtherClass {
private WhateverClassThisIs theOtherClass;
public void setTheOtherClass(WhateverClassThisIs theOtherClass) {
this.theOtherClass = theOtherClass;
}
public void whatever() {
String username = theOtherClass.getUsername();
}
}
The other mechanism would rely on passing something in to WhateverClassThisIs with a username setter, roughly:
public class WhateverClassThisIs {
private SomeOtherClass someOtherClass;
public WhateverClassThisIs(SomeOtherClass someOtherClass) {
this.someOtherClass = someOtherClass;
}
private void btnloginActionPerformed(java.awt.event.ActionEvent evt) {
String sql = "select * from userinfo where uname=? and pword=?";
try {
// As before, but:
if (rs.next()) {
someOtherClass.setUsername(txt_username.getText());
}
}
}
}
public class SomeOtherClass {
private String username;
public void setUsername(String username) {
this.username = username;
}
public void whatever() {
// Do something with username--but either try
// after you know it's been set, or by being
// able to handle it being null/empty/whatever
}
}
In addition, you could use an Observer, any of several Swing-ish mechanisms, and so on.
Yes there are ways to do it using reflection ... if the variable is a field.
But the best solution is change the other class so that it has accessible getter and/or setter methods ... after you have thought through all of the implications.
Breaking a classes encapsulation to access private state is something you should only do as a last resort.
If the variable is a local variable, then there is NO way that some other class or method can update it. And you can only access it from another class if that class is a locally declared anonymous inner class and the variable is declared as final. That doesn't sound like what you are trying to do here ....
Related
I have the following class which I'm using as the base of all the models in my project:
public abstract class BaseModel
{
static String table;
static String idField = "id";
public static boolean exists(long id) throws Exception
{
Db db = Util.getDb();
Query q = db.query();
q.select( idField ).whereLong(idField, id).limit(1).get(table);
return q.hasResults();
}
//snip..
}
I'm then trying to extend from it, in the following way:
public class User extends BaseModel
{
static String table = "user";
//snip
}
However, if I try to do the following:
if ( User.exists( 4 ) )
//do something
Then, rather than the query: "SELECT id FROM user WHERE id = ?", it is producing the query: "SELECT id from null WHERE id = ?". So, the overriding of the table field in the User class doesn't seem to be having any effect.
How do I overcome this? If I added a setTable() method to BaseModel, and called setTable() in the constructor of User, then will the new value of table be available to all methods of the User class as well?
You cannot override static methods or fields of any type in Java.
public class User extends BaseModel
{
static String table = "user";
//snip
}
This creates a new field User#table that just happens to have the same name as BaseModel#table. Most IDEs will warn you about that.
If you change the value of the field in BaseModel, it will apply to all other model classes as well.
One way is to have the base methods generic
protected static boolean exists(String table, long id) throws Exception
{
Db db = Util.getDb();
Query q = db.query();
q.select( idField ).whereLong(idField, id).limit(1).get(table);
return q.hasResults();
}
and use it in the subclass
public static boolean exists(long id)
{
return exists("user", id);
}
If you want to use the field approach, you have to create a BaseDAO class and have a UserDAO (one for each model class) that sets the field accordingly. Then you create singleton instances of all the daos.
Because Java doesn't allow you to override static members, you basically need to resort to the slightly more verbose but overall nicer singleton pattern, wherein you're still conceptually writing "static" code, but you're technically using (global/singleton/"static") instances, so you're not restricted by the limitations of static.
(note that you also need to use methods because fields don't participate in polymorphism, and thus cannot be overridden)
public abstract class BaseTable {
public abstract String table();
public String idField() { return "id"; }
public boolean exists(long id) {
// don't build queries this way in real life though!
System.out.println("SELECT count(*) FROM " + table() + " WHERE " + idField() + " = " + id);
return true;
}
}
public class UserTable extends BaseTable {
public static final User INSTANCE = new UserTable();
private UseTabler() {}
#Override public String table() { return "user"; }
}
public class PostTable extends BaseTable {
public static final Post INSTANCE = new PostTable();
private PostTable() {}
#Override public String table() { return "post"; }
}
public static void main(String[] args) {
UserTable.INSTANCE.exists(123);
PostTable.INSTANCE.exists(456);
}
Outputs:
SELECT count(*) FROM user WHERE id = 123
SELECT count(*) FROM post WHERE id = 456
In order to do what you are looking to do, don't make table static in the BaseModel. Then in the other classes that inherit from BaseModel, you can set table in the default constructor to whatever you wish.
static {
table = "user";
}
So I'm developing a software that uses mongodb/morphia and I need a way to listen that object to check when a certain value changes to update it in the database instead of doing it manually.
What's the best way to do it? Observer Pattern?
So I have 3 classes: User(super class), GlobalPlayer and my Main.
I know I need to use an Observer Pattern but I'm having questions while implementing.
User Class:
GlobalPlayer Class:
Main Class:
As you can see on my main class I'm updating my GlobalPlayer every 5 seconds even if that same don't have any new update, so how can I implement the observer pattern into this?
Use a dirty flag.
With an observer pattern you can track each change. But do you really want to save each user every time a little change is done? Probably not, so when using an observer you might also want to build something that prevents too high a database load by delaying writes. Also, I always try to keep my Dataobjects simple, with loose connections, as this reduces complexity. Thus my guess is that an observer pattern is overkill and makes it more complicated than needed. Just using a dirty bit and a scheduled task to save each user periodically. Not much load and only minor data loss in case of a system crash.
public class User {
#Transient
boolean dirty;
private void markDirty() {
dirty = true;
}
public void isDirty {
return dirty();
}
Each setter, should first call the markDirty() method. Like this:
public void addCoins(long coins) {
markDirty();
this.coins += coins;
}
And in Global we only save a user when he/she/it/other is dirty:
if (gp.isDirty()) {
getPlayerManager().update(gp);
}
An even better design would move the if(gp.isDirty()) to the update of the PlayerManager class, as it should be the responsibility of the Playermanager when to save.
As jjohns pointed out, you can use Observers and Observables
Edit
He probably didn't mean that. As of Java 9, this observer pattern is deprecated.
One alternative is to declare your own event that subclasses EventObject:
class UserChangeEvent extends EventObject {
private String actionCommand; // additional property for more control
public UserChangeEvent(Object source, String actionCommand) {
super(source);
this.actionCommand = actionCommand;
}
public String getActionCommand() { return actionCommand; }
}
Then, declare an interface that will handle the events (onUserChange(UserChangeEvent) will be the "callback" method):
interface UserChangeListener {
/**
* Fired when any user property changes
* #param event
*/
public void onUserChange(UserChangeEvent event);
}
Here's a sample User class:
class User {
private List<UserChangeListener> changeListeners = new ArrayList<UserChangeListener>();
private String username;
private String email;
public User(String username, String email) {
this.username = username;
this.email = email;
}
/**
* Registers a UserChangeListener instance that will be notified when any setter is called
* #param listener the new event listener
*/
public void addUserChangeListener(UserChangeListener listener) {
changeListeners.add(listener);
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username; // actually set the username
UserChangeEvent event = new UserChangeEvent(this, "username"); // a new instance of our custom user change event
// fire user change event for all event listeners
for (UserChangeListener listener:changeListeners) {
listener.onUserChange(event);
}
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
UserChangeEvent event = new UserChangeEvent(this, "email");
for (UserChangeListener listener:changeListeners) {
listener.onUserChange(event);
}
}
}
Here's a simple implementation of User, UserChangeEvent, and UserChangeListener:
public class Test {
public static void main(String[] args) {
User hworld1234 = new User("hworld1234", "hworld#example.com");
hworld1234.addUserChangeListener(new UserChangeListener() {
#Override
public void onUserChange(UserChangeEvent event) {
String actionCommand = event.getActionCommand(); // what we gave our custom event in the setters
if ("username".equals(actionCommand)) {
System.out.println("username has been changed to '" + hworld1234.getUsername() + "'");
} else if ("email".equals(actionCommand)) {
System.out.println("email has been changed to '" + hworld1234.getEmail() + "'");
}
}
});
hworld1234.setEmail("hworld#gmail.com"); // prints "email has been changed to 'hworld#gmail.com'"
}
}
If you prefer, another way of doing this is to declare an onXXXChange for each property to be "bound" and forget the actionCommand property; although, if you even have more than one method in an interface, you should probably turn it into an adapter.
This is a fairly rudimentary question but one that I am kind of on the fence about. Lets say I have a class A and it has methods method1,method2,method3,method4 and a main method.
method2 is only invoked by method1;
method4 is only invoked by method3.
The solution says to invoke the method1 from main and also method2 from main and same with method3 and 4.
So isn't it bad design to have the main method invoke method1, and method2 explicitly? What is the point of having private methods in a class if you invoke them in the main method even though they are only dependent on a single method in the whole class?
Wouldn't it be cleaner to call method2 from method1 and method4 from method3 since in both cases the latter method is only invoked by the former?
I thought this was the whole point of helper methods, so that we are able to abstract away unnecessary details of the implementation.
Again my apologies for the simplicity of the question, I am quite new to java.
Class A{
public static void main(String[] args){
int x = method1()
if ( x = 0){
//user wants to create a new account
method2()
}
}
private static int method1(){
//some code to check user login credentials in list of users
//if login credentials fail,user is asked if they want to create a new account, if yes,
//method 2 is invoked
//return value is whether the user wants to create a new account or not.
}
private static void method2(){
//creates new account for user and is only invoked by method1.
}
}
In the above case wouldn't it just be easier to call method2() from method1() instead of calling it in the main(). I would like to know if there are any advantages or disadvantages of this style of implementation.
In general terms, this is an exercise in separation of concerns. First, let's give your methods real names:
checkUserAccount(name, password)
addNewUserAccount(name)
Now, suppose you write checkUserAccount() so that it calls addNewUserAccount() if the user name is not found. In this case, the main program has no way of calling a function to just check the user credentials. The main program has no choice but to check the user account and then a new account will be added if the user isn't found. This is not very flexible if you decide to change things later.
On the other hand, if you separate these actions then the main program can decide what to do itself in the case where a user account is not found. You can then write code that looks something like what you showed:
if (checkUserAccount(name, password)) {
// great! logged in
} else {
addNewUserAccount(name);
}
This allows you to easily modify the main program if you choose to add a new feature. For example:
if (checkUserAccount(name, password)) {
// great! logged in
} else {
if (newUsersPermitted) {
addNewUserAccount(name);
} else {
System.out.println("Sorry, this system is closed.");
}
}
Of course, a real login system will have many more details to consider.
It's just a pseudocode, just to give you an idea.
public class User {
String name;
String username;
String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Here you can leave your queries
public class UserDAO {
public Boolean checkUsername(User user){
//here you use the object User
//ex: user.username, user.password in your query
String sql = "select bla bla bla";
if(sql){
//save something in log(just a example for a private method)
saveLog();
return true;
}else{
return false;
}
}
private Boolean saveLog(){
String sql = "insert bla bla bla";
if(sql){
return true;
}else{
return false;
}
}
}
Here is your main class
public class Test {
public static void main(String[] args) {
User u = new User();
u.setUsername("john");
u.setPassword("6876sdh");
UserDAO dao = new UserDAO();
Boolean ret = dao.checkUsername(u);
if(ret){
System.out.println("OK");
}else{
System.out.println("No Ok");
}
}
}
A full simple example: http://www.roseindia.net/tutorial/java/jdbc/dataaccessobjectdesignpattern.html
I had a class for a db connection like that (simplified):
public class SQL {
private static SQL instance = null;
private static String ADRESS;
private SQL() {
try {
// Settings
settings = Settings.getInstance();
ADDRESS = settings.getAdress;
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://" + ADRESS + "...");
}
catch (SQLException e) {
throw e;
}
}
public static SQL getInstance() {
if(instance == null) {
instance = new SQL();
}
return instance;
}
public String select(...) {
// SELECT Code
}
public String update(...) {
// UPDATE Code
}
public String insert(...) {
// INSERT Code
}
}
But now I need two variants of SQL and they mainly differ only in the settings (different databases). So I wanted to make SQL to an abstract class and overwrite only the constructor in the two inherited classes.
But as far as I could find out it's not possible to have an abstract private constructor!?
So how can I change the class SQL to an abstract class then?
Thanks, I hope someone understands the problen :)
I would use something like this:
public static SQL getOrMakeInstance1() {
if(instance1 == null) {
instance1 = new SQL(pram11,param12,param13);
}
return instance1;
}
public static SQL getOrMakeInstance2() {
if(instance2 == null) {
instance2 = new SQL(pram21,param22,param23);
}
return instance2;
}
-maybe is a factory pattern, I don't know the names from design patterns :)
I hope it helps.
I'm not sure you need more than 1 class. What if you changed your class's constructor to take a Settings instance?
public SQL(Settings settings){
ADDRESS = settings.getAddress();
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://" + ADRESS + "...");
}
Then what you make different Setting instances
Settings settings = ...
SQL sql = new SQL(settings);
Settings differentSettings =...
SQL differentSql = new SQL(differentSettings);
maybe anybody could help me out. i'm working with Data access object.
i have a database:
table Receiverz
num name
1 Walmart
2 Target
3 McDonalds
i've created a class for this table
public class Receiverz {
private int num;
private String name;
public void setNum(int num) {
this.num = num;
}
public void setName(String name) {
this.name = name;
}
}
then i created Dao interface and passed a method to it:
public interface Dao {
Receiverz getReceiverz(int num);}
Then i created a class ExpensesDao that implements Dao and created a singleton in it(i aslo set up the connection with database but i will skip that part) and overrode getReceivers(int num) method by making it possible to work with database:
public class ExpensesDao implements Dao {
private static Dao thisdao;
public static synchronized Dao getDao() {
if (thisdao==null) {
thisdao = new ExpensesDao();
}
return thisdao;
}
#Override
public Receiverz getReceiverz(int num) {
Receiverz receiver = new Receiverz();
try {
Statement stmt = myConnection.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM receiverz");
while(result.next()){
receiver.setNum(num);
receiver.setName(result.getString(2));
}
}
catch (SQLException e){
System.out.println(e.getMessage());
}
return receiver;
}
when i try to run it in main class:
public class TryDatabase {
public static void main(String[] args) {
Dao ex = ExpensesDao.getDao();
System.out.println(ex.getReceiverz(2));
all i get is:
listexpenses.Receiverz#193499fd
but i have to get
2 Target
(since i passed 2 in the parameters and it refers to Target in my database.
does anyone know what's going wrong and what i should change in my code. P.S. i hope i made it clear enough.
ex.getReceiverz(2) is returning a Receiverz object. Thus the System.out.println(ex.getReceiverz(2)); is using the toString() method inherited from java.lang.Object. Create a toString() method in the Receiverz class that will output it the way you want.
add a getName to your recieverz and change to this ex.getReceiverz(2).getName()
A bit offtopic, but I recommend the double checked locking singleton code to avoid all concurrency issues in initalization.
Ps.: ex.getReceiverz(2).getName() breaks Law of Demeter, might be better to avoid it.