I am having problems understanding how private and public variables work.
I am trying to fill the myStorage.outString variable from myThread.
But it seems I cannot see the setInString method from myThread.
Here is my example:
public class CT63_Console extends MIDlet {
public Storage myStorage;
public void startApp() {
this.myStorage = new Storage();
}
}
public class storage{
private String[] outString;
public Storage(){
AClass myThread = new AClass();
myThread.start();
}
public void setInString(String sendString){
this.outString = sendString; //push seems not to be supported by MIDP
}
}
public class AClass{
public void run(){
myFunction("write this into Storage var outString");
}
private myFunction(myString){
myStorage.setInString(myString);
}
}
What do I have to do to set the variable and why am I wrong?
You are trying to access myStorage without having a reference to it.
You could pass this reference when you create the AClass instance.
Also, you are trying to assign a String to an array of Strings which can't be done.
public class Storage{
private String outString;
public Storage(){
AClass myThread = new AClass(this);
myThread.start();
}
public void setInString(String sendString){
this.outString = sendString; //push seems not to be supported by MIDP
}
}
public class AClass {
Storage myStorage;
public AClass(Storage s) {
this.myStorage = s;
}
public void run(){
myFunction("write this into Storage var outString");
}
private myFunction(String myString) {
myStorage.setInString(myString);
}
}
this.outString = sendString;
outString is an array of strings (String[]). You cannot assign a single string to an array of strings. So either you need to change the type of that variable to a single string (just String), or you need to specify an index where you assign that string to. Note that in the latter case you need to initialize the array first.
Related
Yes, I read many examples in web, but I didn't find a way how to call a method based on string value. May be I am not searching in right way... I wrote all code, but don't know how to call the method.
fyi: I don't want to use if else or switch case
Here is what I want:
I get the card reader type as String from database. I have to call the corresponding class' method.
My code:
LoginPanel.java
public class LoginPanel {
public static void main(String args[]) {
String readerType = "Omnikey5427-CK"; // I get this ("Omnikey5427-CK" or "Omnikey5427-G2") from a database as String
// I WANT TO CALL getCardNumber() method of respective class
}
}
ISmartCardReader.java
public interface ISmartCardReader {
public Integer getCardNumber();
}
Omnikey5427G2.java
public class Omnikey5427G2 implements ISmartCardReader {
public Omnikey5427G2() {
System.out.println("G222222222222222...");
}
public Integer getCardNumber() {
return 222;
}
}
Omnikey5427CK.java
public class Omnikey5427CK implements ISmartCardReader {
public Omnikey5427CK() {
System.out.println("CKKKKKKKKKKKKKKK...");
}
public Integer getCardNumber() {
return 111;
}
}
SmacrtCardEnumFactory.java
public enum SmacrtCardEnumFactory {
OMNIKEY5427CK("Omnikey5427-CK") {
public ISmartCardReader geInstance() {
return new Omnikey5427CK();
}
},
OMNIKEY5427G2("Omnikey5427-G2") {
public ISmartCardReader geInstance() {
return new Omnikey5427G2();
}
};
private String cardReaderName;
private SmacrtCardEnumFactory(String cardReaderName) {
this.cardReaderName = cardReaderName;
}
public String cardReaderName() {
return cardReaderName;
}
}
You can use valueOf() function of enum provided your enum sonstant names match strings used to lookup (you may use cardName.toUpper()). You may also create objects for all the card types and store them in a hash map and then lookup them. You can also write some fatory method, but this will be if-then-else or switch inside
You could iterate over the factory's values() and get the one that matches the string:
public enum SmacrtCardEnumFactory {
// current code omitted for brevity
public static getSmartCardReader(String name) {
return Arrays.stream(values())
.filter(r -> r.cardReaderName().equals(name))
.map(SmacrtCardEnumFactory::getInstance();
.orElse(null);
}
}
This is a continuation from what I was working in Passing 1 to many parameters of same object type
I've gotten good feedback on that , I believe i have the improved the design . The whole code is at https://github.com/spakai/flow_input_builder
The requirement is simple : -
I need to build a set of input for different workflows using 1 or more outputs from previous workflows
I have a set of interfaces
public interface SwfInput {
}
public interface SwfOutput {
}
public interface Workflow<I extends SwfInput, O extends SwfOutput> {
public O execute(I input);
}
public interface Builder<I extends SwfInput> {
public I build();
}
Now , Say I have 3 flows which gets executed in sequence FlowA->FlowB->FlowC
FlowC needs mandatory output from FlowB but only optionally from FlowA
so I have a implementation for FlowCBuilder
public class FlowCInputBuilder implements Builder<FlowCInput> {
private final FlowBOutput mandatoryflowBOutput;
private FlowAOutput optionalflowAOutput;
public FlowAOutput getOptionalflowAOutput() {
return optionalflowAOutput;
}
public FlowCInputBuilder setOptionalflowAOutput(FlowAOutput optionalflowAOutput) {
this.optionalflowAOutput = optionalflowAOutput;
return this;
}
public FlowCInputBuilder(FlowBOutput mandatoryflowBOutput) {
this.mandatoryflowBOutput = mandatoryflowBOutput;
}
#Override
public FlowCInput build() {
FlowCInput input = new FlowCInput();
input.setMandatoryFromFlowB(mandatoryflowBOutput.getOutput1FromB());
if (optionalflowAOutput != null) {
input.setOptionalFromFlowA(optionalflowAOutput.getOutput2FromA());
}
return input;
}
}
one test i have written shows an example usage
FlowBOutput mandatoryflowBOutput = new FlowBOutput();
mandatoryflowBOutput.setOutput1FromB("iNeedThis");
FlowAOutput optionalflowAOutput = new FlowAOutput();
FlowCInput input = new FlowCInputBuilder(mandatoryflowBOutput)
.setOptionalflowAOutput(optionalflowAOutput)
.build();
I have not used static inner class for the Builder pattern.
Any suggestions are welcomed.
You should use static inner class. The key point of using this approach is that, the inner can directly access private properties of the object being constructed. This helps eliminating duplicated code since the builder does not need to maintain a long list of temporary state for the constructing. So, your code can be rewritten like this:
public class FlowCInput {
private int output1FromB; // suppose that it is int
private String output2FromA; // suppose that it is String
private FlowCInput() { }
//...
public static class FlowCInputBuilder implements Builder<FlowCInput> {
private final FlowCInput result;
public FlowCInputBuilder(FlowBOutput mandatoryflowBOutput) {
result = new FlowCInput();
// output1FromB is private but still accessed from here
result.output1FromB = mandatoryflowBOutput.getOutput1FromB();
}
public FlowCInputBuilder setOptionalflowAOutput(FlowAOutput optionalflowAOutput) {
// same for output2FromA
result.output2FromA = optionalflowAOutput.getOutput2FromA();
return this;
}
#Override
public FlowCInput build() {
return result;
}
}
}
As you see, the builder now holds only a FlowCInput object, it does not unnecessarily hold mandatoryflowBOutput and optionalflowAOutput as before.
I have a class with this, it's an example code, not the real code
private static String className;
public static Wish getInstance(Class<?> clazz) {
if(wish == null)
wish = new Wish();
className = clazz.getName();
return wish;
}
Many classes use this Wish class, then each class should "say" a wish with the className passed in the getInstance method.
Then I have something like this
public class Boy {
private Wish w = Wish.getInstance(Boy.class);
//at this moment the static variable take "com.package.Boy" value
....
}
Another classs
public class Girl {
private Wish w = Wish.getInstance(Girl.class);
//at this moment the static variable take "com.package.Girl" value
....
}
When everybody start to say their wishes, example
public class WishesDay {
private Girl g;
private Boy b;
public void makeYourWish() {
g = new Girl(); //get the com.package.Girl value
b = new Boy(); //get the com.package.Boy value
//sample output "com.package.Boy wants A pink house!"
g.iWish("A pink house!"); // the boys don't want this things :(
b.iWish("A spatial boat!");
}
}
I know that each object have the same copy o the Wish class and the static variable className change when each object (Girl, Boy) call the Wish.getInstance(Class<?> clazz) method.
How can I use a static variable (I want avoid to instantiate the Wish class) and keep the correct value for the variable className.
Can I make this with a static variable? or the solution is to instantiate (no static variable)
For example, log4j has the Logger class, I want to make the same thing with the class name.
You'll have to make your constructor private if you want to avoid instantiate the Wish class and make the className not static.
public class Wish {
String className;
private Wish(String className){
this.className = className;
}
public static Wish getInstance(Class<?> clazz) {
String className = clazz.getName();
return new Wish(className);
}
public String getClassName() {
return className;
}
}
package com.test;
public class WishesDay {
private Girl g;
private Boy b;
public void makeYourWish() {
g = new Girl(); //get the com.package.Girl value
b = new Boy(); //get the com.package.Boy value
//sample output "com.package.Boy wants A pink house!"
g.iWish("A pink house!"); // the boys don't want this things :(
b.iWish("A spatial boat!");
}
public static void main(String[] args) {
WishesDay wd = new WishesDay();
wd.makeYourWish();
//outputs com.test.Girl wants A pink house!
//com.test.Boy wants A spatial boat!
}
}
I come from writing a lot of JavaScript, so bear with me.
I've got 3 HashMaps, which i reference in a method in a different class. My code (very simply) looks like so:
public class MainClass {
private HashMap<String,Nation> randomHashMap = new HashMap<String,Nation>();
DifferentClass d = new DifferentClass(this);
} //with getters/setters
public class DifferentClass {
private MainClass mc;
public void randomMethod() {
System.out.println("randomHashMap is " + (mc.getRandomHashMap() == null));
} //returns null
public DifferentClass(MainClass c) {
this.mc = c;
}
}
However, when I call them in my other method, they're null.
How do I create a new, empty HashMap?
You need to initialize your MainClass mc variable before using it in the DifferentClass#randomMethod method. Also, make sure you're using the mc variable instead of the MainClass.getRandomHashMap() method (by your actual code, we don't know how it behaves). Your code will look like this:
public class DifferentClass {
private MainClass mc = new MainClass();
public void randomMethod() {
//assuming getRandomHashMap is the getter of randomHashMap attribute (and non static)
System.out.println("randomHashMap is " + (mc.getRandomHashMap() == null));
}
}
public class MainClass {
private HashMap<String,Nation> randomHashMap = new HashMap<String,Nation>();
DifferentClass d = new DifferentClass(this);
public HashMap<String,Nation> getRandomHashMap() {
return this.randomHashMap;
}
} //with getters/setters
The code you posted is in fact perfectly all right as far as field initialization. I made an SSCCE from it with minimal intervention:
class Nation{}
public class MainClass {
private HashMap<String,Nation> randomHashMap = new HashMap<String,Nation>();
DifferentClass d = new DifferentClass(this);
public Object getRandomHashMap() {
return randomHashMap;
}
public static void main(String[] args) {
new MainClass().d.randomMethod();
}
} //with getters/setters
class DifferentClass {
private MainClass mc;
public void randomMethod() {
System.out.println("randomHashMap is " + (mc.getRandomHashMap() == null));
} //returns null
public DifferentClass(MainClass c) {
this.mc = c;
}
}
and it prints
randomHashMap is false
which proves that randomHashMap is indeed non-null.
I have encountered a weird problem in my app (java).
I have an enum. Something like that
public enum myEnum implement myIntrface{
valueA(1),valueb(2),valuec(3),valued(4)
private int i;
// and then - a constructor
public MyEnum(int number){
i = number;
}
private MyObj obj = new MyObj;
// getter and setter for obj
}
and in another class I have this
MyEnum.valueA.setObj(new Obj(...))
in briefe - I have an enum with a private instance member that has a set and a get.
So far so good -
The only thing that amazes me is that later on I look at the value of the MyEnum.valueA().obj is null.
there is nothing that updates the value to null, I have even gave it a default value in the constructor and I still see it null later.
any suggestions?
Enums should be un-modifiable classes so you shouldn't really be doing this. If your looking to modify the state of a type based object like an enum you should use an final class approach with embedded constants. Below is an example of a class based approach with a modifiable name an a un-modifiable name...
public final class Connection {
public static final Connection EMAIL = new Connection("email");
public static final Connection PHONE = new Connection("phone");
public static final Connection FAX = new Connection("fax");
/**/
private final String unmodifiableName; //<-- it's final
private String modifiableName;
/*
* The constructor is private so no new connections can be created outside.
*/
private Connection(String name) {
this.unmodifiableName = name;
}
public String getUnmodifiableName() {
return unmodifiableName;
}
public String getModifiableName() {
return modifiableName;
}
public void setModifiableName(String modifiableName) {
this.modifiableName = modifiableName;
}
}
The purpose of enums is to represent constant values. It does not make any sense to set the fields of a constant value.
You should declare your fields as final, and use the constructor to initialize all of them.
For reference, the following code works as expected:
public class Test {
public static enum MyEnum {
valueA(1),valueb(2),valuec(3),valued(4);
private int i;
private Object o;
private MyEnum(int number) {
i = number;
}
public void set(Object o) {
this.o = o;
}
public Object get() {
return o;
}
}
public static void main(String[] args) {
System.out.println(MyEnum.valueA.get()); // prints "null"
MyEnum.valueA.set(new Integer(42));
System.out.println(MyEnum.valueA.get()); // prints "42"
}
}
the cause of this problem is the db40 framework . It loads an enum from the db using reflection. This is well documented .
http://developer.db4o.com/Forums/tabid/98/aft/5439/Default.aspx