lundi 16 février 2015

is it possible to declare a Java Class variable using getClass()?

All of the relevant classes in my application instantiate a version of the class Logger as logger = new Logger(). Any class can invoke it's instance of logger.setText(String text).


The writeText(Object parameter) method in ClassA is built to get the previously set string from each class instance of logger by invoking it's instance of logger.getText().


Currently I've placed a conditional inside wrtieText for each of the classes. This works, but can become an issue if I end up adding more classes. I want a catch-all writeText method to accommodate for any new classes that may be added.


The following is the currently working model. Beneath this, I have included the alternate version of ClassA, which attempts to do what I'm describing by using the getClass() method.


ClassA.java



public class ClassA {
public static void main(String[] args) {
ClassA classA = new ClassA();
classA.execute();
}

public void execute() {
ClassB doSomething = new ClassB();
writeText(doSomething);

ClassC doSomethingElse = new ClassC();
writeText(doSomethingElse);
}

public void writeText(Object parameter) {
if(parameter instanceof ClassB) {
ClassB x = (ClassB) parameter;
System.out.println(x.logger.getText() + "\n\n");
}

if(parameter instanceof ClassC) {
ClassC x = (ClassC) parameter;
System.out.println(x.logger.getText() + "\n\n");
}

if(parameter instanceof ClassD) {
ClassD x = (ClassD) parameter;
System.out.println(x.logger.getText() + "\n\n");
}
}
}


Logger.java



public class Logger {
private String text = "";

public void setText(String text) {
this.text = text;
}

public String getText() {
return this.text;
}
}


ClassB.java



public class ClassB {
Logger logger = new Logger();

public ClassB() {
logger.setText("Hello from ClassB!");
}
}


ClassC.java



public class ClassC {
Logger logger = new Logger();

public ClassC() {
logger.setText("Hello from ClassC!");
}
}


I'm trying to invoke the getClass() method in order to account for any class with the following, but it's running into some problems.


ClassA.java



public class ClassA {
public static void main(String[] args) {
ClassA classA = new ClassA();
classA.execute();
}

public void execute() {
ClassB doSomething = new ClassB();
writeText(doSomething);

ClassC doSomethingElse = new Class();
writeText(doSomethingElse);
}

public void writeText(Object parameter) {
Class aClass = parameter.getClass();

// now what? The following doesn't work as expected
aClass x = (aClass) parameter;
System.out.println(x.logger.getText());
}
}





Aucun commentaire:

Enregistrer un commentaire