I do have one class that has one instance variable, that is being injected like below:
public Class HierarchyAccessor {
#Inject
HierarchyProvider provider;
public int GetAllHierarchies(HierarchyAccessorInput input) {
String requiredVariable = input.getId;
provider.provideHierarchy(requiredVariable);
}
}
Here, I do have another class HierarchyHelper, that has one static function which is performing some operation by creating an object of class HierarchyAccessor.
public Class HierarchyHelper {
public static List<String> getHierarchies() {
// Here I want to create the object of HierarchyAccessor.
// this is not working .
HierarchyAccessor accessor = new HierarchyAccessor();
/*
It performs some operations and returns the required output.
*/
}
}
So, here I'm unable to create the object of HierarchyAccessor class inside the static method, due to some constraint, I can't change this static method to non-static.
Can someone please suggest how to create the object of HierarchyAccessor inside the static method?
Related
I am making a simulator for solving problems in Java. I want to create a task where a person needs to create class A and then in class B, in the main method, create objects of class A. The problem is that I don't know how to check the number of created objects, or at least the fact that objects were created. Can I check the creation of objects? Without making changes to classes A and B ?
public class A {
//some code
}
class B {
public static void main(String[] args) {
//User will have to create an object of class A here
}
}
You can check the number of objects created in a class by keeping a static variable and increment it upon creation automatically. For example, for class A:
class A {
private static int noOfObjects = 0;
{
numOfInstances += 1;
}
//constructors and other methods
public static int getNumOfInstances() {
return numOfInstances;
}
}
Remember, static variables initialized only once, and they're shared between all instances.
Need a variable to hold a value which will be assigned once and will be used by every method of a class
if I specify it as non static variable it is not holding the value
Class Test{
private String test;
public void method1(){
test = "String1";
}
public void method2(){
System.out.println(test.length());
}
}
Getting Null Pointer exception. the value of the test will be used in every method.
Could anyone help me, how to fix the issue.
The NullPointerException will be thrown whenever the test variable is null and you try to invoke methods on that variable. In your case, when you invoke method2() before method1(). That has nothing to do with global, local or whatever, as Long Vu already mentioned.
So first you should make sure, you don't access an uninitialized variable. Then, if you need a class with a single instance, which should be accessible application wide, you can implement this using the singleton pattern. For more about it, have a look at this Wikipedia page: https://en.wikipedia.org/wiki/Singleton_pattern
Maybe your problem is that you are creating multiple objects of class Test.
For example this should work:
Test test1=new Test();
test1.method1(); //call this first then other methods
test1.method2();
You should use this object "test1" as a parameter wherever you need it.
If you want to access the variable globally then create a Singletone class:
class Test{
private static Test single_instance = null;
private String test;
// private constructor restricted to this class itself
private Test(){
}
// static method to create instance of Singleton class
public static Test getInstance(){
if (single_instance == null)
single_instance = new Test();
return single_instance;
}
public void setTest(String value){
test = value;
}
public String getTest(){
return test;
}
public static void main(String args[]){
Test test = Test.getInstance();
test.setTest("String1");
test.getTest();
}
}
The Java reflection code in my Android application invokes a public static method in a package B, from a package A.
Recently, after some Gradle upgrades, I am unable to invoke the same method. My implementation fails with a NoSuchMethodFound exception. How can I get the implementation to be able to find this method?
I've tried printing all the available methods from the class. The result is all public non-static methods. No static methods are available to be invoked. The method I want to invoke is a static "getInstance" method which initializes the class and returns a singleton instance.
Calling Code:
implementationClass = Class.forName(CLIENT_CLASS_NAME, false, ClientProvider.class.getClassLoader());
final Method method = implementationClass.getMethod("getInstance", (Class[]) null);
result = method.invoke(null, (Object[]) null);
Called Code:
/**
* Public static method to be reflected.
*/
public static ClientImpl getInstance() {
return ClientImplHolder.INSTANCE;
}
/**
* Private class used to hold the lazily initialized singleton instance.
*/
private static class ClientImplHolder {
private static final ClientImpl INSTANCE = new ClientImpl();
}
When attempting to 'getMethod', I receive a NoSuchMethodException.
Not sure what I am doing wrong here, appreciate any help. Thanks!
Turns out Proguard was removing the method from the build since it was not being used elsewhere. Added an exception for the class and the issue went away.
If i understood correctly, you used reflection API wrong
just try this.
public class Test {
public static void main(String[] args) {
try {
ClientImpl client = (ClientImpl) Class.forName(ClientImpl.class.getCanonicalName())
.getMethod("getInstance")
.invoke(null);
System.out.println(client.toString() + " with some -> " + client.getSome());
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Public static method to be reflected.
*/
class ClientImpl {
private final int some;
public int getSome() {
return some;
}
private ClientImpl(int some) {
this.some = some;
}
public static ClientImpl getInstance() {
return ClientImplHolder.INSTANCE;
}
/**
* Private class used to hold the lazily initialized singleton instance.
*/
private static class ClientImplHolder {
private static final ClientImpl INSTANCE = new ClientImpl(123);
}
}
and it will put correctly result
ClientImpl#<hashcode> with some -> 123
When you use static methods in reflection API, you don't need to call it ClassLoader explicitly, you have to put it's canonicalName in argument, then you can call it's methods.
Try to replace it,maybe it's a parameter problem.
final Method method = implementationClass.getMethod("getInstance");
result = method.invoke(null);
Starting in Android 9 (API level 28), the platform restricts which non-SDK interfaces your app can use. These restrictions apply whenever an app references a non-SDK interface or attempts to obtain its handle using reflection.
I came across a code which my colleague uses inside an eventListner, which is :
private void someActionPerformed(java.awt.event.ActionEvent evt) {
new className().methodName(); //public class and public void methodName()
}
I was pretty sure that :
private void someActionPerformed(java.awt.event.ActionEvent evt) {
className ref = new className(); //public class and public void
ref.methodName();
}
is the better option than his, as the previous method instantiates a class every time it is called.
Am I wrong? Any suggestion is appreciated, Please correct me if I am wrong
.
Both do the same thing, however one of them (the first) is 1 line shorter.
Your approach is usually recommended when you need to go through more than 2-3 objects, so new Foo().getBar1().getBar2().doStuff() is usually not recommended since it can degrade into spaghetti code and hinder the understandability of the code.
The first code-sample instantiates a new Object of Type className.methodName.
For this to work, methodName has to be a static nested class of Type className.
Attention: This could as well be a typo. Did you mean new className().methodName()?
The second sample creates a new instance of className and calls its method methodName.
Some example code:
public class Test {
public static void main(String[] args) {
new Test.test(); // instantiates the inner class
Test t = new Test(); // instantiates Test
t.test(); // calls method #test of Test-instance
}
public String test() {
return "Test";
}
public static class test {
}
}
In order to judge what's the best solution your example does not give enought information. Is the method some static utility code or is an instance of className useful? It depends...
Whenever an object is instantiated but is not assigned a reference variable, it is called anonymous object instantiation.
With anonymous object you can call it's instance method also:
new className().methodName();
In your case this is the anonymous object which doesn't have reference variable.
In the statements:
className ref = new className();
ref.methodName();
ref is the reference variable to hold the className object, so you can call instance methods of className on ref variable.
The benefit of using anonymous notation is, if you want to do only limited (may be calling single method and so on..) operation with the underlying object the it is a good approach. But if you needs to perform more operation with the underlying object then you need to keep that object in a reference variable so that you can use that reference to perform multiple operations with that object.
Regarding the performance there are not much difference as both are in methods scope, as soon as method completes both the objects are valid candidates for the garbage collection.
Both the methods instantiates a class in the code. If you want to reuse the class object every time the method is called, you can declare it as a member of the class where the method resides. For eg:
class AnotherClass{
private ClassName ref;
AnotherClass(){
ref = new ClassName()
}
private void someActionPerformed(java.awt.event.ActionEvent evt) {
ref.methodName();
}
}
This way, everytime your method someActionPerformed is called on an object of AnotherClass, it will reuse the ref object instead of instantiating it everytime.
About the edit,
public class ClassName {
static class InnerClass{
// A static inner class
}
public void methodName() {
// A method
}
}
class AnotherClass{
private void someActionPerformed(java.awt.event.ActionEvent evt){
// This creates an instance of the inner class `InnerClass`
new ClassName.InnerClass();
// However I believe, you wanted to do:
new ClassName().methodName();
}
}
new className.methodName(); --> if you are using this convention in your code then calling another method name will result to different object's method name and you lose your values.
className ref = new className();
ref.methodName(); -> here you are creating a reference and make assiging a newly created object and you are calling the method's on it. Suppose if you want to call another method on the same object it will helps.
The first approach they will mostly use for listenere which is anonymous class.
Both options create a new Class every time they are called. The advantage of the second over the first option would be if you wanted to reuse that class later in the method.
IMHO this is a little bit more understandable code for the answer provided by DaniEll
public class Test {
public static void main(String[] args) {
new Test.test(); // instantiates the inner class
Test t = new Test(); // instantiates Test
t.test(); // calls method #test of Test-instance
}
public void test() {
System.out.println("Outer class");
}
public static class test {
public test() {
System.out.println("Inner class");
}
}
}
Scenario is like this:
There is a field in database 'overAllCount' which contains some value.
I have to use this variable in many classes I am designing.
I want to fetch this 'overAllCount' in one class say 'OverAllCountClass' and use it in all subclasses with its class name like OverAllCountClass.overAllCount. Basically like a static variable.
How can I do it?
My solution is:
public Class OverAllCountClass {
public static int OverAllCount;
public OverAllCountClass(){
// Fetch overAllCount from database here and set its value
}
}
////////// Use it like this //////////////
public class Usecount {
public void abc(){
// BUT IT IS NOT POSSIBLE becuase OverAllCountClass is not yet initialize
int mycount = OverAllCountClass.overAllCount
}
}
How can I achieve this?
If your concern is, the static variable overAllCount, might not get initialized and if you want it to get initialized whenever the class OverAllCountClass first gets invoked, then you can use Static initializer blocks
public class OverAllCountClass {
public static int overAllCount;
static {
overAllCount = fetchOverAllCount();
}
}
A static initializer block is invoked first time a class gets loaded. And a class gets first loaded when JVM sees that its been used.
public class Usecount {
public void abc(){
//When JVM sees that OberAllCountClass is used here, it executes the static block of OverAllCountClass and by the time below statement is executed, overAllCount is initialized
int mycount = OverAllCountClass.overAllCount
}
}
public Class OverAllCountClass {
protected int overAllCount; //will allow you to use in subclass too
public OverAllCountClass(){
// Fetch overAllCount from database here and set its value
}
public int getOverAllCount(){
return overAllCount;
}
}
public class Usecount {
//pass the instance of overAllCountInstance to UseCount somehow using constructor or setter
private OverAllCountClass overAllCountInstance;
public void abc(){
int mycount = overAllCountInstance.getOverAllCount();
}
}
No need to use static over here. Use getter to get the count
Rather than having a public static variable which can be modified/abused by other classes. I would provide a specific API which can hide the implementation and do things like lazy-loading if needed:
public static final Value getValue(){
//evaluate private field
return value;
}
This API can be a static method or be a singleton scoped method, depending on use case.
Another option is to make OverAllCountClass a Singleton.
public class OverAllCountClass {
private static final OverAllCountClass instance = new OverAllCountClass();
private Integer overAllCount = null;
// make it non-instanciable outside by making the constructor private
private OverAllCountClass {
}
public static OverAllCountClass getInstance() {
return instance;
}
public int getOverAllCount() {
if (overAllCount = null) {
//get value from database and assign it
}
return overAllCount;
}
}
This has the benefit that to code that accesses OverAllCountClass it is transparent wether it's a Singleton or not. This makes swapping out the implementation easier.