I have a few different button layouts for some controllers mapped inside nested classes. Here's an example:
public class ControllerMap{
public static class Type1{
public static final int BUTTON_A = 1,
BUTTON_B = 2;
}
public static class Type2{
public static final int BUTTON_A = 2,
BUTTON_B = 1;
}
}
I want to make a variable to reference which one to use throughout my code. Something like layout = ControllerMap.Type1;. I'm pretty sure this isn't actually possible, but is there any other way I can do this?
If you want them to be used as layout templates, you could do something like this:
public class Template
{
public static final Template type1 = new Template(1, 2);
public static final Template type2 = new Template(2, 1);
public int buttonA;
public int buttonB;
public Template(int buttonA, int buttonB)
{
this.buttonA = buttonA;
this.buttonB = buttonB;
}
}
And then you can use the layout variable like this:
public static Template layout = Template.type1;
Yes you could refer it from anywhere since both your class are public and class variables are public too like:
int button = ControllerMap.Type1.BUTTON_A;//from anywhere and is resolved at compile time
But if you need it runtime, you could just inject appropriate instance and create getter/setter instead of exposing the field directly.
I think you are trying to use 'static' in an OO way which will never work. In this case you can use the Strategy Pattern to solve your issue, but you will have to adapt your code.
Make your class Type1 and Type2 implement a interface (iController). Then anywhere in your code you can can assign:
iController controller = new Type1();
Related
Hi want to add new field boolean hasXYZ to an existing class which has two member variables. This class is widely used in the code and I want to add the new field in a way that I do not want to change all of the
new demoClass() calls to include the new field hasXYZ. And I was hasXYZ more like a on demand field .. so effectively, I guess two set of constructor .. one which works and other which takes additional boolean and sets hasXYZ. Thoughts on how I can do this ?
#Value
#NonFinal
public class demoClass implements demoInterface {
int integerMember;
long longMember;
}
Overload the constructor:
public class demoClass implements demoInterface {
int integerMember;
long longMember; // these should probably be private
boolean hasXYZ;
public demoClass( int integerMember, long longMember) {
this.integerMember = integerMember;
this.longMember = longMember;
}
public demoClass( int integerMember, long longMember, boolean hasXYZ) {
this.integerMember = integerMember;
this.longMember = longMember;
this.hasXYZ = hasXYZ;
}
}
Then you won't have to modify how you create the objects.
I have an abstract class which is supposed to have an (int) attribute that can't be modified after initialization and is pre-set to 1; what is the best way to do it?
Should I make it final?
The requirement is that inside the class I will have one and only one constructor(with parameters), and no setters.
If so, how do I make it 1 by default if it's final and (I suppose) I'm going to initialize it in the constructor?
Thanks!
As a matter of fact your can even hard code it, if it will always be a constant value.
For example if your variable should always be 25 you can do something like this:
public abstract class Test
{
protected final int pressure = 25;
//Constructor
public Test()
{
// TODO Auto-generated constructor stub
}
}
But if you evaluate the value on runtime you need to set it with in the constructor of the Object:
public abstract class Test
{
protected final int pressure;
//Constructor
public Test(int pressure)
{
this.pressure = pressure;
}
}
Note that in this case the variable must not be assigned earlier!
The question, if a final variable should be used depends on it's purpose. A final variable can only be assigned once over it's entire lifetime. If you have to modify it in any kind you should not use it.
You could use constructor overloading to achive this. See the example:
public abstract class TestClass{
private final int otherParam;
private final int fixedParam;
public TestClass(final int otherParam){
this.otherParam = otherParam;
this.fixedParam = 1;
}
public TestClass(final int otherParam, final int fixedParam){
this.otherParam = otherParam;
this.fixedParam = fixedParam;
}
}
You should use a constructor with parameters to set your initial values. Then, as you say, don't create any setter, and be sure your fields are private, so that no one can access it.
This way, you will do what you want, having fields initialized but never change after that.
I have a REST API test suite where certain URIs are used repeatedly. Thus, I created a separate class with public static final members. Something like:
public class RestURI {
public RestURI(){}
public static final String getAllShipsURI = "/ship/manager/ships";
public static final String getAllPortsURI = "/port/manager/ports";
}
However, is there a way to deal with URIs like this:
/infrastructure/ships/docked/" + shipId + "/capacity
I am looking for a way such that I can declare the URL like above in the RestURI class and still specify values in the test when I use them.
You can use a constant format, rather than a String and use a static getter:
public static String getShipUri(int shipId) {
return String.format("/infrastructure/ships/docked/%d/capacity", shipId);
}
You could use String.format. Like this:
public class RestURI {
public RestURI(){}
public xxx() {
int shipId = 219001000;
... String.format(dockedShipURIFormat, shipId) ...;
}
public static final String dockedShipURIFormat = "/infrastructure/ships/docked/%d/capacity";
}
I've used ANTLR StringTemplate for exactly this on multiple occasions. The ability to have inline macro parsing and a little if..else logic in the templates is pretty powerful, and it maintains good readability.
So I'm trying to cut back on some of the code that's been written. I created a separate class to try this. I have that class working correctly, however the old one uses variables that are now in the separate class. How do I access these variables? Unfortunately I can't share all the code for this, but I can give out small pieces that I think are necessary. Thanks for the help
This is from the old class that I am now trying to bring the variable to: I'm trying to bring "loader" over
// XComponentLoader loader = null;
fixture.execute(new OpenOfficeOpener());
component = loader.loadComponentFromURL("file:///"+System.getenv("BONDER_ROOT") + "/ControlledFiles/CommonFiles/"+spreadsheet, "_blank", 0, loadProps);
You can write getters for the members that you need to be visible outside. Example:
public class MyClass {
private int member1;
private String member2;
public int getMember1() {
return member1;
}
public String getMember2() {
return member2;
}
}
Now both member1 and member2 can be accessed from the outside.
There are a couple of solutions to your problem. What I would suggest is to add a method in your class to return the value to the new program, or pass it as a parameter.
An example of this on a higher level might look like this:
x = newClass.getValX()
It sounds like you're looking for a static field, though if is the case you almost certainly reconsider your current design.
public class YourClass {
private static XComponentLoader loader;
public YourClass() {
YourClass.loader = new XComponentLoader();
}
}
And to access it from another class:
public YourOtherClass {
public void yourMethod() {
YourClass.loader ...
}
}
If loader is static, than do something like:
component = TheOtherClass.loader.loadComponentFromURL( ...
Otherwise, your new class needs a reference to an instance of the other class. You could pass it with the constructor:
public class NewClass {
private OldClass oldClass = null;
public NewClass(OldClass oldClass) {
this.oldClass = oldClass;
}
// ...
fixture.execute(new OpenOfficeOpener());
// assuming, loader is a public field on OldClass.
// a getter (getLoader()) is preferred
component = oldClass.loader.loadComponentFromURL("file:///"+System.getenv("BONDER_ROOT") + "/ControlledFiles/CommonFiles/"+spreadsheet, "_blank", 0, loadProps);
// ...
}
I've you've split functionality into two classes, then you may want to have one class instantiate another.
If you've put your new code in Class B then it might look like this.
public class A {
// Class B instance
B b = new B();
public void doSomething() {
b.loadComponentFromURL("someurl");
}
}
Or if the loader is an instance itself, you could call it like this.
b.getLoader().loadComponentFromURL("someurl");
I'd like to be able to declare a Java class Ref such that I could, elsewhere in code, do things like this:
switch (v)
{
case Ref.LicenseCode: ....;
case Ref.Widget.MaxWeight: ....;
case Ref.Widget.MolyBolt.ThreadsPerInch: ....;
}
Ref is intended to be constant data structure representing a hierarchical set of constant values, such as often appears in standards documents or other reference material. I want values that are truly constant (so they can be used in a case statement).
I thought I might be able to do this by nesting class definitions, and it works... to a point. For example this:
public final class Ref
{
public final static int LicenseCode = 800;
public final class Widget
{
public final static int MaxWeight = 5000;
}
}
lets me write this:
switch (v)
{
case Ref.LicenseCode: ....;
case Ref.Widget.MaxWeight: ....;
}
but when I try to nest down to the third level:
public final class Ref
{
public final static int LicenseCode = 800;
public final class Widget
{
public final static int MaxWeight = 5000;
public final class MolyBolt
{
public final static int ThreadsPerInch = 12;
}
}
}
I am told that:
"Ref.Widget.MolyBolt cannot be resolved or is not a field."
Am I doing something wrong? Or have I bumped up against one of the edges of Java? Is there some other way to accomplish my goal? I am running under Windows Vista, JCK 1.6.0-21, using Eclipse Java Development Tools 3.5.2.r352.
Looks like bill of material information to me. Embedding this in Java classes as static data seems to be terribly rigid to me. It's far more natural to store it in a relational, hierarchical, object, or graph database.
The other problem is that the code to process this will be a spaghetti forest of if/then/else or switch statements to process.
It's hard to overstate just how wrong-headed this appears to be. You might get an answer that will allow you to proceed, but this can only end in grief.
How are you referencing the ThreadsPerInch field? This works for me:
public final class Ref {
public final static int LicenseCode = 800;
public final class Widget {
public final static int MaxWeight = 5000;
public final class MolyBolt {
public final static int ThreadsPerInch = 12;
}
}
public static void main(String[] args) {
int v = Integer.valueOf(args[0]);
switch (v) {
case Ref.LicenseCode:
break;
case Ref.Widget.MaxWeight:
break;
case Ref.Widget.MolyBolt.ThreadsPerInch:
break;
}
}
}
The only thing I'd change is to make inner classes static, though you're probably not going to instantiate any objects of this class anyway.