How does a method signature of only "static" work? [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Static initializer in Java
I have a few years' experience with Java, but I've recently run across something I've never seen before:
public class Project{
...
static{
initDataTypeMapping();
}
...
}
How does this method signature work? Is this in fact even technically a method? I'm wondering why one wouldn't simply put the the method call to initDataTypeMapping() in the constructor. Just trying to increase my understanding so I don't mess something up. Thanks!

This is known as a static initializer.
The code in the static { } block is run when the class is first loaded by the classloader (which is usually, but not always, when code that refers to the class is first loaded/executed), and is guaranteed to be run in a thread-safe manner.
See this question also.

Related

JAVA: Getting a count, how many times a class is being called in other classes [duplicate]

This question already has answers here:
How to Count Number of Instances of a Class
(9 answers)
Closed 4 years ago.
Suppose I have a demo.java class and have other classes like A.java , B. Java and so on.
I want to write some code in Demo.java to get the count , that will tell in how many classes Demo.java is getting called.
Any suggestions would help. Thanks in advance!
Create a static variable in class.
public static int callerCounter=0;.
And then increment it in every constructor. E.g:-
Demo()
{
callerCounter++; // Add this line in every Constructor
}
And Print callerCounter where you want to get counter value.
I do not think it is doable in general case by just analyzing the code. If the interface is in use, may not be trivial to know which class will be instantiated behind the interface. This may depend on decision within some factory and may influenced by the input that is only available at runtime, well, even by SecureRandom theoretically.
You can always put either counters or just logging statements (processing the log output separately) to collect this kind of statistics at runtime. Tools like JProfiler may work as programming-free alternative.
Create a static Set callerClasses to hold the name of each class that called your Demo class.
Then, at each call to your Demo class, add the caller name to the set.
At any point in time you can check how many different classes called your Demo class by inspecting the Set size.
EDIT NOTE #1:
The question was made clear after I posted my answer that the intention is not count for calls on methods but count instances created.
I will keep it anyway because this may be the case for someone else.
EDIT NOTE #2:
Added code sample for completeness.
public class Demo {
// ConcurrentSkipListSet for thread safety
private static Set<String> callerCount = new ConcurrentSkipListSet<>();
public void methodA() {
String className = new Exception().getStackTrace()[1].getClassName();
recordCaller(className);
}
public long getNumberOfCallers() {
return callerCount.size();
}
private void recordCaller(final String className) {
callerCount.add(className);
}
}

Does Java have an equivalent keyword to static in C? [duplicate]

This question already has answers here:
How do I create a static local variable in Java?
(8 answers)
Closed 6 years ago.
I know that in C, when the keyword static is used on a local variable, it causes that variable to remain initialized between function calls (i.e. when the variable goes out of scope). For example:
int myFunction() {
static int i = 3;
i++;
return i;
}
If myFunction() is called twice, it will return 4 the first time and 5 the second time (because i keeps its value between the two calls rather than being reinitialized the second time).
My question is this: does Java have an equivalent keyword to static in C? Java also has the keyword static, but it is used completely differently than in C.
Not exactly, but a private static class level variable will almost do the same thing.
But
it will be visible to all other methods of the class as well
it will be initialized not on first method call, but when the class itself is loaded
I suppose that is workable.
All variables in a method are local to the function and placed on the stack. The closest you have is a static variable in a class.
If you make the variable private and place the method in a class of it's own you will achieve much the same result.
(With a private constructor)
It's somewhat similar to the private keyword, as in C a static global variable or a function is visible only in the file it's declared in...
So that's probably the closest you will find :)
No, because all methods and functions are bound to classes in Java, so there is no "global space" as there is in C. The static keyword in Java has different semantics.
See the docs for static and this post for more detail on the differences.
Java uses static in a different manner. To get the same result you want here, you should use a private field instead.

RuntimeExtension.class -- What does the ".class" mean? [duplicate]

This question already has answers here:
What does .class mean in Java?
(8 answers)
Closed 8 years ago.
I've read the docs for the Junit ExpectedException class, and the parameter for the .expect() method seems to be implemented strangely in all the examples I've studies. When you pass in the expected exception type, it has a .class extension that doesn't appear to be a method of any kind.
Can someone please explain this syntax? Thank you. Example code is below:
public ExpectedException thrown = ExpectedException.none();
public void testPlusException() {
thrown.expect(RuntimeException.class);
Vector testVector = vector1.plus(vector3);
}
Calling .class on a type gets the class object of the particular type. You can read more about the specifics here.
http://docs.oracle.com/javase/tutorial/reflect/class/classNew.html
Although it's not mentioned in the Java documentation for the Object class, all classes derived from Object have a public static Class<T> class member that stores the runtime type of said object.
It's also what gets returned when you call getClass() on an object, keeping in mind that all methods in Java are virtual.

Invoking a method by its name [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I invoke a Java method when given the method name as a string?
I have 10 methods named: m1, m2, m3,...
like this:
public void m1(){
..
}
How do I invoke them with string in a 'for' loop?
I want to do this:
for (int i=1;i<11;i++){
invoke('m'+i);
}
You need to use reflection to achieve this.
Method method = getClass().getMethod(methodName);
method.invoke(this);
So, you need to store your method names in an array and use this code piece to call those methods one by one.
You can do this with reflection.
However, I would be interested in your use case. Often it is possible to refactor an application, so that the use of reflection is superfluous.
Use java reflection on this object.

what does static { // some code } mean? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Static Initialization Blocks
What does the following mean in java?
static {
WritableComparator.define(IntPair.class, new Comparator());
}
That means static initialization block which will be executed on class load.
If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate. Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.
It means that the code within that block will run once, when the type is loaded, before any constructors are called, but after any field initialisers are run.
Note that you cannot set any instance fields in the static block. There is no concept of this in there, just as in any other static methods.

Categories