For example, I have three classes:
public class A{public static void doSth(){}}
public class B{public static void doSth(){}}
public class C{public static void doSth(){}}
Then I have a variable:
private int controlVariable;
Then based on the value of this controlVariable, I want to invoke the doSth() method in different class above. For example:
switch (i)
{
case 1:
A.doSth();
break;
case 2:
B.doSth();
break;
case 3:
C.doSth();
break;
}
However, using the above approach is very tedious. Can I use a variable to store the name of class. For example:
classNameVariable = A;
classNameVaribale.doSth();
Can anyone help me with this? Please do not use inheritance.
In Java 8 you could use method references:
public class A {
public static void doSth() {
System.out.println("A");
}
}
public class B {
public static void doSth() {
System.out.println("B");
}
}
public class C {
public static void doSth() {
System.out.println("C");
}
}
public class Sample {
public static void main(String[] args) {
Runnable[] methods = { A::doSth, B::doSth, C::doSth };
int controlVariable = 2;
methods[controlVariable].run(); // C
}
}
In this example, controlVariable is a 0-based index.
I believe using A.getClass().getSimpleName() will return a string with the class name as given in the source code.
You can use reflection to get class from class name:
Class cls = Class.forName("your class package");
Method method = cls.getMethod("methodName", arguments);
Object o = method.invoke(null, "whatever");
Hope this will help you.
Related
If there are 3 methods in
public class Hero extends GameCharacter {
public void test1(){};
public void test2(){};
public void test3(){};
is it possible while running this in
public class MainClass extends ApplicationAdapter implements InputProcessor {
#Override
public void create () {
private Hero mainHero;
For (int x = 0; x < 0; x++)
....
to run
mainhero.testx
?
This situation is suitable for Strategy Pattern. Basically you have a variation in functionality, so you create an interface for executing it, and create multiple implementations of it. It could look something like this:
package test;
public class Test {
public static interface TestStrategy {
void test();
}
public static class Test1 implements TestStrategy {
#Override
public void test() {
System.out.println("1");
}
}
public static class Hero {
TestStrategy test[] = new TestStrategy[]{
//either use defined class
new Test1(),
//or inline
() -> {System.out.println("2");}
};
}
public static void main(String[] args) {
Hero hero = new Hero();
for (int i = 0; i < hero.test.length; i++) {
hero.test[i].test();
}
}
}
You could using reflection, but you should evaluate better patterns for this.
Alternative solutions include
Conditionals
public void test(int x){
switch (x) {
case 1:
// Things for x == 1
break;
}
};
OOP, for when you have different types of Heroes
public abstract class Hero extends GameCharacter {
public abstract void test();
}
public class Hero1 extends Hero {
#Override
public void test() {}
}
...
List<Hero> heroes = ... ;
heroes.add(new Hero1());
for (Hero h : heroes) { h.test(); }
Or, just call all your test methods separately via independent unit-testing methods.
Like suggested before, you could use reflection for this. This example uses reflection to demonstrate that.
public void callYourClassMethod(String x) {
try {
YourClass yourClass = new YourClass()
Method method = YourClass.class.getDeclaredMethods("methodname" + x);
method.setAccessible(true); // Only needed if it's not accessible from calling class.
method.invoke(yourClass); // Assuming your method doesn't take any arguments.
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
System.err.println("Method methodname" + x + "is not declared.");
e.printStackTrace();
}
}
public interface Counter{
class Base1{
protected int count1;
public Base1(){
count1=0;
}
#Override
public void putCount(){
System.out.println(count1);
}
}
}
How to access putCount() in interface's class method and count1 variable?
Try this:
Counter.Base1 myBase1 = new Counter.Base1();
myBase1.putCount();
The concept is called inner class, if you want to find further information. As count1 is protected, you cannot access it from the outside.
We tried to understand your query & this is what we got.
Plz check it
public interface Counter{
class Base1{
protected static int count1;
public Pblm(){
count1=0;
}
public static void putCount(){
System.out.println(count1);
}
}
}
The example below show how to call method of class inside an interface.
interface Outer1 {
public abstract void show();
class Inner1 {
public void display() {
System.out.println("Hello 1");
}
}
}
public class Test extends Outer1.Inner1 {
public static void main(String args[]) {
Test t1 = new Test(); t1.display();
}
}
See more at: link
i'm trying to write anonymous inner class
interface Face{
void seeThis(String what);
}
class Eyes {
public void show(Face f){}
}
public class Seen {
public void test() {
Eyes e = new Eyes();
e.show(new Face() {
#Override
public void seeThis(String what){
System.out.print(what);
}
});
public static void main(String[] args) {
Seen s = new Seen();
s.test();
}
}
How to call seeThis() and how to pass parameter to it?
Method seeThis() belongs to Face class, which instance is anonymous and thus cannot be reached without storing reference to it. If you want to store a reference, you can do this in the following way:
public class Seen {
public Face face;
....
this.face = new Face() { ... };
e.show(this.face);
And then,
Seen s = new Seen();
s.face.seeThis();
Now, regarding passing the parameter. You have two options - declare parameter outside of anonymous class and make it final in order to be reachable by this anonymous class, or replace anonymous class with normal one and pass the parameter to its constructor:
Approach one:
final int parameter = 5;
...(new Face() {
#Override
public void seeThis() {
System.out.println(parameter);
}
});
Approach two:
public class MyFace implements Face() {
private final int parameter;
public MyFace(int parameter) {
this.parameter = parameter;
}
#Override
public void seeThis() {
System.out.println(parameter);
}
}
Then,
...
e.show(new MyFace(10));
Okay, here's the setup:
EnclosingClass {
public interface ClassFactory {
public static SomeClass getInstance(int which);
}
private static ClassFactoryImpl {
#Override
public static SomeClass getInstance(int which) {
switch(which) {
case 1:
return new SomeClassSubclassA();
case 2:
return new SomeClassSubclassB();
...
}
}
}
}
I would like to be able to issue statements along the line of:
SomeClass x = EnclosingClass.ClassFactory.getInstance(instanceClassRequest);
Is this possible? If not, how can I access a static nested class through only the interface it implements?
The short answer is "no." You'll need to make an instance of your implementation class and put it in a static variable. It'll look like this:
public class EnclosingClass {
public interface ClassFactory {
public SomeClass getInstance(int which);
}
public static final ClassFactory CLASS_FACTORY;
private static class ClassFactoryImpl implements ClassFactory {
public SomeClass getInstance(int which) { /* ... */ }
}
static {
CLASS_FACTORY = new ClassFactoryImpl();
}
}
Also note that the method on the instance is no longer static.
Then code that invokes it would look like this:
SomeClass x = EnclosingClass.CLASS_FACTORY.getInstance(2);
Consider the following code in Python:
class A(object):
CLASS_ATTRIBUTE = 42
def f(self):
return "CLASS_ATTRIBUTE: %d" % self.CLASS_ATTRIBUTE
class B(A):
CLASS_ATTRIBUTE = 44
Now A().f() and B().f() return "CLASS_ATTRIBUTE: 42" and "CLASS_ATTRIBUTE: 44" respectively.
How can I achieve a similar effect in Java? I want a CLASS_ATTRIBUTE field to be initialized statically and redefined in the inherited class but the f method should be only defined in the base class.
Is there a particular reason you want the attribute to be static? In Java the typical way you'd do this is to have A contain a protected variable that you then set in the constructors of the 2 classes:
public class A
{
protected int CLASS_ATTRIBUTE;
public A()
{
CLASS_ATTRIBUTE = 42;
}
public String f()
{
return "CLASS_ATTRIBUTE: " + CLASS_ATTRIBUTE;
}
}
public class B extends A
{
public B()
{
CLASS_ATTRIBUTE = 44;
}
}
Alternatively (and probably more consistent with Java design patterns) you'd declare a function that you can override to return the value instead of using a member variable.
Short answer: you cant solve it like this in Java. You'll have to solve it in another way.
In Java you can't override or "redeclare" fields in subclasses, and you can't override static methods.
It can be solved using an ugly reflection-hack (should be avoided though):
public class Main {
public static void main(String... args) {
A a = new A();
B b = new B();
System.out.println(a.f()); // Prints 42.
System.out.println(a.fReflection()); // Prints 42.
System.out.println(b.f()); // Prints 42.
System.out.println(b.fReflection()); // Prints 44.
}
}
class A {
static int CLASS_ATTRIBUTE = 42;
public int f() {
return CLASS_ATTRIBUTE;
}
public int fReflection() {
try {
return getClass().getDeclaredField("CLASS_ATTRIBUTE").getInt(null);
} catch (Exception wontHappen) {
return -1;
}
}
}
class B extends A {
// Compiles, but will not "override" A.CLASS_ATTRIBUTE.
static int CLASS_ATTRIBUTE = 44;
}
You can't do this directly with only a variable, because in Java variables cannot override (they only shadow the super classes variables).
You need to use a protected "getter" method, which can then be overridden by the subclass:
class A
{
private int attribute=42;
...
protected int getAttribute() {
return attribute;
}
}
class B
extends A
{
private int attribute=44;
...
protected int getAttribute() {
return attribute;
}
}
But note there's a special consideration to calling methods from an object's constructor, in that it allows object code to run before object construction is complete.
I'm not sure if you meant "statically" literally or not, but here's a brief example of how inheritance at it's most basic form looks in Java. Note that using a getter method to access the variable is a better idea for several reasons -- this is just an example.
public class Dog {
protected String whatISay = "Woof!";
public void speak(){
System.out.println(whatISay);
}
}
public class Poodle extends Dog {
public Poodle(){
whatISay = "Yap!";
}
}
public class Main {
public static void main(String[] args){
Poodle fluffy = new Poodle();
fluffy.speak();
Dog dog = new Dog();
dog.speak();
}
}
Yap!
Woof!
This way of doing it introduces as little intrusion as I could think of. setAttribute() could be named something like setDefaultValue() if that's clearer.
public class A
{
protected int attribute;
public A()
{
setAttribute();
}
public String f()
{
return "CLASS_ATTRIBUTE: " + attribute;
}
protected void setAttribute()
{
attribute = 42;
}
}
public class B extends A
{
#Override
protected void setAttribute()
{
attribute = 44;
}
}
public class Main
{
public static void main(String[] args)
{
A a = new A();
B b = new B();
System.out.println("A: " + a.f());
System.out.println("B: " + b.f());
}
}