Getting static fields values of Build class - java

There is Build.SERIAL static field for instance. Is there another way to get this value rather than just reading it from static field?

Something like this can work. Only reason why someone would use it, I can think of private static field, witch can be accessed only form class where it is declared. You can get access from another class through getter method.
private static String abcd = "ABCD";
public String getAbcd(){
return this.abcd;
}

Related

Replacing static variables in a test

I have a helper class with some static final strings as follows
public static final String abc = "abc"
In my test though, I want to use the value
public static final String abc = "xyz"
So I added the following
private static final HelperClass mock = mock(HelperClass.class);
#Before
when(mock.abc).thenReturn("xyz")
The actual code to test
public void codeToTest() {
// use Helperclass.abc
// other logic
But this declaration is not allowed since it needs to be a method invocation. (MissingMethodInvocation) How do I use the static variables in the test?
Static values can make some tests a bit more difficult. You won't be able to use mocking to get this value. But I have to ask why you would want to mock this. It isn't testing anything in the helper class to access this variable and you are wanting a constant, why not just define and use the constant in your test?
Create Another Mocked class as below.
private static class MockedHelperClass extends MockUp<HelperClass>
{
public static final String abc = "xyz"
#Mock
String getABC()
{
return abc;
}
}
Then use this mocked class as below in Test Method
MockedHelperClass helperClass = new MockedHelperClass();
helperClass.abc = "xyz";
helperClass.getABC();
You should re-think your design, changing static variables in tests isn't a good practice. However, if you really want to to that, you can use reflection.
static void setStatic(Field field, Object value) throws Exception {
field.setAccessible(true);
Field modifiers = Field.class.getDeclaredField("modifiers");
modifiers.setAccessible(true);
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, value);
}
Invocation example:
setStatic(MyClass.class.getField("abc"), "xyz");

Should I use static method or static fields

I want to declare some static variables and use them a lot in my code, so in this example if I want to change the phone number I will change it in one place:
public class AppInformation{
static String phone_number="44444444";
}
So now I could get the phone_number by calling the class :
AppInformation.phone_number;
Another solution:
public class AppInformation {
public static String get_phone_number(){
return "44444444";
}
}
Now I could call the method:
AppInformation.get_phone_number();
Actually I prefer the second method because it is thread safe!
Is this correct? Are there any other suggestions?
Declare it as public static final String PHONE_NUMBER = "44444444". Since you can only read this variable, it is thread-safe.
Why I named it PHONE_NUMBER, not phoneNumber (or breaking all known to me Java conventions phone_number), is explained here.
You can declare it as
static final String phone_number="44444444";
And do not worry about threadsafe anymore :)
What you are saying is that you want a constant, which in Java, is commonly expressed like this:
public class AppInformation
{
public static final String PHONE_NUMBER = "44444444";
}
Note, in your example you've missed:
the access modifier, which in the case of a class means the value would be package private.
the final keywork, which means the value could be modified when the program is running.

What should be the correct way in assigning value to a static variable?

I'm trying to initialize a variable within a class constructor but the IDE is showing this warning:
The static field SoapClient.url should be accessed in a static way.
Can you please check my code below? What should be the correct way to initialize the static variable? Should I ignore the warning or should I just make the variable non-static?
Thanks.
public class SoapClient {
private static String url;
public SoapClient(String url) {
this.url = url;
}
}
The correct way is the static way:
SoapClient.url = ""
But here you probably need a regular field:
public class SoapClient {
private final String url;
public SoapClient(final String url) {
this.url = url;
}
}
When a variable is static, this means that you'll have one url for all instances, and not per object. You don't want each construction of an object to change url. However, if you still want to do this, you can access it like SoapClient.url.
(In your code, url will always hold the value of the last constructed object).
That warning comes out of accessing the variable url through the this. variable, which refers to the current instance of the object.
The main problem, however, comes from assigning a static variable inside the constructor. What is the behavior you wish? Do you really need that every time you build a new SoapClient object, the static url is rewritten for EVERY instance of SoapClient? Or would you need every client to store a different url (which sounds way better to me)? In that case, I would just implement the url field as a regular field like someone else has suggested (just take out the static modifier from the field declaration)
There are two ways
public Login(String url) {
Login.url = url;
}
But static varible is created only once in the class, so why you initialize it in the constructor. you can create another static method and initialize url in that.
public static void setUrl(String url) {
Login.url = url;
}
A static variable is specific to the class, while a member variable is specific to an instance of the class. When we think to a SoapClient, you may think its URL is specific to each different instance of the class, as each SoapClient might have a different URL address.
This means it might be better to remove the static keyword from URL.
If you use url as a member variable, you have correctly intanstiated it.
If you want to use it as a static variable, use:
SoapClient.url = url;
Taken from Oracle:
Sometimes, you want to have variables that are common to all objects.
This is accomplished with the static modifier. Fields that have the
static modifier in their declaration are called static fields or class
variables. They are associated with the class, rather than with any
object. Every instance of the class shares a class variable, which is
in one fixed location in memory. Any object can change the value of a
class variable, but class variables can also be manipulated without
creating an instance of the class.
So You have two options:
public class SoapClient {
private String url;
public SoapClient(String url) {
this.url = url;
}
}
Or:
public class SoapClient {
private static String url = "http://stackoverflow.com";
public SoapClient() {
}
}

Java - Any way to make variable unmodifiable after being set in the constructor?

I have a member variable that in a class that I want to make sure nothing changes it after it is set in the constructor. So, it would look something like this:
public class MyClass
{
private String myVar = null;
public MyClass(DataObj dataObj)
{
myVar = dataObj.getFinalVarValue();
//at this point I don't want anything to be able change the value of myVar
}
....
}
My first thought was to see I could just add the final modifier to the variable, but the compiler complains about assigning a value to the final field. Is it possible to accomplish this?
The compiler complains (in the constructor), because you already provide an initialization by writing
private String myVar = null;
remove the '= null' part. Add final and assign the value in the constructor.
public class MyClass
{
private final String myVar;
public MyClass(DataObj dataObj)
{
myVar = dataObj.getFinalVarValue(); // the only assignment/init happens here.
}
....
}
Make it private, and then don't include a setter. As long as you never change it in within the class methods, it's immutable.
String objects are already immutable. So adding the private final modificator is enough.

object created within a class gets access to private fields.. and objects created in a different class don't why?

First of all i created a class called PrivateShirt1 and called a private field name after creating an object of the class within the same class file, and it worked.
public class PrivateShirt1{
private String name;
public static void main(String args[]){
PrivateShirt1 s1=new PrivateShirt1();
s1.name="hi";
System.out.println(s1.name);
}
}
next i created a separate file called PrivateShirt2 in which i put the main method of PrivateShirt1 and performed the function of compiling and calling it. After the modifications the files PrivateShirt1 and PrivateShirt2 look like this:
public class PrivateShirt2{
public static void main(String args[]){
PrivateShirt1 s1=new PrivateShirt1();
s1.name="hi";
System.out.println(s1.name);
}
public class PrivateShirt1 {
private String name;
}
and when i compiled the PrivateShirt2 file, it gave an error that the attribute i was trying to call is private.
but then why did this not happen in the previous example? I mean, objects were created in both the cases and hence the rules should be equal for both, right? so why then this partial treatment? could anyone elaborate?
You need to look at java access control. The name variable in PrivateShirt1 has private access. Meaning that field can only be referenced from inside that class. PrivateShirt2 does not have access to that field. The reason your first call worked is because it was called within PrivateShirt1
http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
private modifier means that you can access it only from the code in the Class. Therefore you can access a private member from a static method or even an inner class.

Categories