Get name of class during static construction - java

In C# I can assign the name of a class to a local static variable like this.
public class MyClass
{
private static string TAG = typeof(MyClass).Name;
}
I've found this very useful, because the value of the string automatically updated if the class is refactored to another name. Handy for tagging debug messages and such.
Is something like this possible in Java?
public class MyClass
{
private static String TAG = ????;
}
I know I could use getClass().getName() but that requires a reference to an object. Is there a way to do this on a static variable?

You don't need to assign the name of a class to field instead of writing.
MyClass.TAG
you can write
MyClass.class.getName();
If you really need to you can assign this to TAG but I don't see the point.

A trick is also available that does not require programmer's knowledge of the class name beforehand:
public class MyClass
{
private static String TAG =
new Object() { }.getClass().getEnclosingClass().getName();
}
This trick uses a nested anonymous Object subclass to get hold of the execution context. It has a benefit of being copy/paste safe in case of cloning your code across different classes...

Related

How to modify an encapsulated library in Java?

I am using a generator for my project. Problem is now I need to modify this library's some methods according to my needs.
Generator class is final so I can't create a new class that extends it. Also putlast method is private.
Is there a way to solve this problem or I need to remove this library?
My main method;
generator.setFlowProperty(myProperty);
Library classes;
public final class Generator{
public Builder setFlowProperty(Property property) {
putLast("flowProperty", property.toCustomString());
....
}
private Builder putLast(String name, String value) {
....
}
}
public final class Property{
public String toCustomString(){
return "a" + prop; // I want to modify this and return "b"+ instead of "a"+.
}
}
There is no way you can inherit final class. I suppose library author made Generator class not for overriding. Anyway you can create your own class with logic you want.
If you want to override only a few functionalties of the library and leave most of them as they are, you can create a class that wraps the library class, only modifying the desired behaviours. So, the main purpose of this class will be to serve as a proxy before the library class, except when you want to modify some behaviour.

Setting Java Enums values through dependency injection

I created a class with a public nested enum class and some setters. The nested enum class uses variables with values from a properties file set through dependency injection to the outer class. I want the component that uses the outer class to be agnostic of the values of the enum and loop through each one individually. The enum will always be instantiated after the outer class so there's no worry about null values in the variables. I was told this isn't how enums are supposed to be used. The suggestion is to write a class that mimics the enum class instead of just using the enum. That seemed very dogmatic and I'm curious what people's thoughts are and possible alternatives. I had written something like:
public class myOuterClass {
private static string1;
private static string2;
private static string3;
public enum NestedEnum {
MY_ENUM1("enum1: "+string1),
MY_ENUM2("enum2: "+string2),
MY_ENUM3("enum3: "+string3);
private String enumValue = "";
NestedEnum(String enumValue) {
this.enumValue = enumValue;
}
public String getEnumValue() { return enumValue; }
}
public String printEnum(NestedEnum enum) {
System.out.println(enum.getEnumValue());
return enum.getEnumValue();
}
public void setString1(String string1) {
this.string1 = string1;
}
public void setString2(String string2) {
this.string2 = string2;
}
public void setString3(String string3) {
this.string3 = string3;
}
}
The problem with your approach is that your enums are not actually dependency-injected; rather, they own their own instantiation logic (as enums always do), and they simply rely, in a fragile and unenforceable way, on dependency-injection having completed before the enum class is loaded by the class-loader. (Note that, since the enum is public, you aren't really controlling when this will happen; and neither is your DI framework.)
One way to fix this is to have your enum's constructor call into your DI framework. (For example, if you're using Guice and have a singleton instance of your Injector, your enum's constructor can ask it for the appropriate instances, thereby guaranteeing the ordering.) This is not ideal -- it pollutes your class code with references to your DI setup -- but it's better than what you have.
Another approach, of course, is not to use enum to begin with: let your DI framework do its job and manage your instances for you. But it sounds like you've already rejected that approach; and who am I to argue?
Edited to add: another potential issue with your approach is that the only way to "reset" your enums is by stopping and restarting the JVM. If you have multiple versions of your properties-file (e.g., different language versions), then your test-framework probably will not be able to test that they all work properly. (My first suggestion above does not address this issue.)

Singleton or static class?

I have the following class :
public class EnteredValues {
private HashMap<String, String> mEnteredValues;
public boolean change = false;
public boolean submit = false;
private static final EnteredValues instance = new EnteredValues();
// Singleton
private EnteredValues() {
mEnteredValues = new HashMap<String, String>();
}
public static EnteredValues getInstance() {
return instance;
}
public void addValue(String id, String value) {
if (mEnteredValues.put(id, value) != null) {
// A change has happened
change = true;
}
}
public String getValueForIdentifier(String identifier) {
return mEnteredValues.get(identifier);
}
public HashMap<String, String> getEnteredValues() {
return mEnteredValues;
}
public void clean() {
mEnteredValues.clear();
change = false;
submit = false;
}
}
This class is used to manage the values that a user has already entered, and the class should be accessible to all classes across the application.
When the activity changes I 'reset' the singleton by calling the clear method.
I chose the singleton pattern without really considering the option of a static class.
But now I was wondering if I shouldn't just use a static class..
What is the common way to handle a class that just manages values?
Is a static class faster as a singleton?
thx
The very fact that you are providing a clear method to reset the state of your Singleton dictates that you should not use Singleton. This is risky behavior as the state is global. This also means that unit testing is going to be a big pain.
One more thing. Never ever declare instance variables as public. Declare them as private or protected and provide getters and setters. Also, there is no need to initialize instance variables with a value that is their default value.
The main difference between a static class and the singleton pattern is that singleton may be used if you need to implement an interface or such. For this particular case I think you might be better off with a static class since you are not implementing any interface. Relating your question if its one faster to the other, I'd say is negligible the difference but using a static class will remove a small overhead of dynamic instantiation of the class.
What is bad in using singleton if you need such a design? If you need exactly one instance of some object designed to do specified things singleton is not a bad choice for sure.
#see Are Java static calls more or less expensive than non-static calls?
Read
http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
From there:
Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
Just for style
I prefer not to rely on Singleton if I don't need to. Why? Less cohesion. If it's a property you can set from outside, then you can test your Activity (or whatever) with unit testing. You can change your mind to use diferent instances if you like, and so on.
My humble advise is to have a property in each of your Activities (maybe you can define a common base class?), and set it at activity initialization with a new fresh instance.
Your code will not know nothing about how to get it (except the init code and maybe you can change it in the future).
But as I've said... just a matter of taste! :)

How can I approximate having a static variable in an Inner class?

I am working on a series of classes that all inherit from a single, base, abstract class.
In order to keep track of all of these child classes, I'd like to implement something like a GUID -- for my purposes, it doesn't have to be an actual GUID, just an int that is unique to each instance of a child class. An incremented int is what I'd been hoping to use.
What I'd have liked to do, is implement the following in my abstract class:
abstract class ParentObject{
static int GUID = 0;
//other stuff
}
whereafter each child class, in its constructor, would have myGUID = GUID++;
However, whenever I try this, I get the following error from the Processing IDE:
The field GUID cannot be declared static; static fields can only be
declared in static or top-level types.
Because of how Processing handles class files (everything is an inner class), I can't have static class members. What are my options to duplicate this functionality in other ways?
Edit: This is being done in Processing and the Processing IDE. The ParentObject class is in its own processing file.
Edite2: I have learned that the reason Processing is different from Java is that all Processing classes are Inner Classes. Because of this, I have re-added the Java tag and reformulated the question.
Well, then face it. You can't do it. If you REALLY need it, declare an outer class for handling this piece of code, and call it in the top-level class's constructor.
If you MUST use this hierarchy of innerclass, then you can't do it. Java won't accept it in the way you wan't. You could declare your abstract class as static.
static abstract class ParentObject {
private static int GUID = 0;
}
But I'm almost sure this won't work for you either. So, I suggest to create a new outer class somewhere else to handle it.
public class GUID {
private static int GUID = 0;
public synchronized static void increment() {
GUID++;
}
}
abstract class ParentObject {
ParentObject() {
GUID.increment();
// constructor's stuff
}
}
This may speed down your app (depending on how often you instantiate a class), but not in a significant way.
a static protected method getNextGUID() would work
public abstract class ParentObject{
private static int GUID = 0;
protected static int getNextGUID(){
return GUID++;
}
//other stuff
}
don't forget to synchronize it/use AtomicInteger when you have multiple threads

Accessing data from a data class returning null

OK, I'm not super new to java but for some odd reason I can't figure out why this is not working for me. Basically I have 3 classes in my applet.
My main, my string constructor, and my data class.
The main class calls the string constructor, the string constructor stores its final product into the data class. Last, I'm trying to access the data class using my Main class.
The returned value to the main is always null and I can't figure out why. My suspicion is I'm somehow creating 2 separate data class objects but Ive looked at examples of code and it all seems correct. Here are the classes..
main.
public class LaneGUI extends javax.swing.JApplet {
private laneData laneData;
Timer timer;
/** Initializes the applet LaneGUI */
public void init() {
laneData = new laneData();
xmlParser.parseInputString(connection.getFinalXMLString());
System.out.println(laneData.getLaneID());
string contructor...
public class XMLParser {
private laneData laneData;
public void parseInputString(String input){
try{
/*some xmlparsing*/
laneData = new laneData();
laneData.setLaneID(string);
data class
public class laneData {
private String laneID;
public String getLaneID() {
return laneID;
}
public void setLaneID(String laneID) {
this.laneID = laneID;
}
}
There is a lot of editing here, like in the string class I took out all of the xml parsing and string editing.
Basically, when i check the getLaneID after i set it in the string constructor the value is correct. But when i call a get from the main, its null.
XMLParser and LaneGUI are referring to two different instances of laneData.
Instead of your final line in LaneGUI, which says this:
System.out.println(laneData.getLaneID());
You need something like this:
System.out.println(xmlParser.getLaneData().getLaneID());
You'll also, of couse, need to add a getLaneData() to XMLParser that returns it's laneData instance (or a deep copy thereof.)
As you rightly speculated, you have two different instances of laneData. The XMLParser class has a local instance of laneData different from the instance referenced by LaneGUI.

Categories

Resources