For example, I need to get static property from one of my own classes Class1 or Class2 (property name is same for both classes) depend user action. I have only class name in String variable. How to get this property?
Certainly I can to do this:
InfoClass ic;
if(className.equals("Class1")) {
ic=Class1.prop;
} else if(className.equals("Class2")) {
ic=Class2.prop;
}
But that is not so fine solution, I think... Is there another way to implement this?
You can do this, but as mentioned in the comments it's even less neat than your current solution.
Class clazz = Class.forName(qualifiedClassName);
Field field = clazz.getDeclaredField("prop");
ic = (InfoClass)field.get(null);
It's quite likely that there's a different way to do whatever it is you're doing in your app, which doesn't require reflection or a long list of conditionals; but I don't know enough about your problem to know what that is.
Use reflection:
Class.forName("mypackage.MyClass").getDeclaredField("field").get(null);
Related
I want to create a private Interface in Class A and have it implemented by Class B. My intention is to have a way for Class A to call a method set on class B that NO ONE else can call. They are in separate file in separate packages. Anyone have any ideas?
The best you can achieve is to give the interface package level visibility and move Class A and B into the same package.
This doesn't stop someone adding another class into the same package in the future, thus giving it access to the interface.
short answer is redesign your class structure.
But if you really need to, consider to use reflex feature in java. and you can inject the method although not recommended.
Disclaimer: not a Java programmer.
But if you want to leverage a type system to get compile-time errors... there are often tricks by introducing a new data type as a sort of "access token" or "dummy parameter". Make it hard to get ahold of a value of that type, but require a value of that type as a parameter in the interface.
Yet introducing a hoop like that winds up being about as contrived as renaming your methods alarming things like DoFooActionOnClassB_ButDontCallUnlessYouAreClassA. I think one usually finds that in a good design, this "dummy type" isn't a dummy type at all... but a capture of the context and state that you should have had in the first place.
I understand that you want to have methods on class B which can only be called from class A. One way would be deferring the real check until runtime but let the compiler make it hard to do the wrong thing. So you could try using a secret which only class A can have in order to protect the method in class B.
public class A {
private static final PrivateA PROOF = new PrivateA();
public static class PrivateA {
private PrivateA() { }
// only A can extend PrivateA
}
public static void main(String[] args) {
new B().methodForAOnly(PROOF, "A");
}
}
Here A's PrivateA is a type which only A can instantiate or extend, and B knows about that...
public class B {
public void methodForAOnly(PrivateA proof, String param) {
if (proof == null) throw new NullPointerException();
// do something
System.out.println(param);
}
}
I have a complex object hierarchy that has a couple of extends.
I am looking for a library that can reflectively insert default values on all fields.
For instance:
class Person {
String name;
Color color;
List<Clothes> clothes;
}
class Child extends Person {
Sibling sibling;
}
class Foo {
Person person;
Child child;
}
I would like a library that take an object as parameter, in this case the Foo class, and then reflectively insert default values (even better if I can define default values) on all fields. Also all maps,list,sets etc should get a new
I have looked at BeanUtils, but to my knowledge, it doesn't support exactly what I am looking for.
NB: These are just examples, and my objects are much more complex and big. They have many objects, and each object has many objects and so on. Both with maps, lists etc.
Is it maybe better to combine some libraries like BeanUtils and Google Guava and make it my own?
It should be fairly simple to do in one method provided you have the structure already built (in when case setting them as you build is a more logical approach)
If you know the default values in advance, why not just set them in the class? (i.e. default, default values ;)
Is there much value in setting a default name for a person (other than null) Can you give an example of where you would want to specify the default value dynamically?
Personally I would just try to use normal java constructors, and/or getters and setters etc. However from the question I'm guessing you want something that can work without knowing the exact structure of your classes.
So if you really have to do this, you could probably do something along the lines of the following:
public void setFields(Object myObject) {
Class<?> clazz = myObject.getClass();
Field[] fields = clazz.getFields();
for(Field field : fields) {
String name = field.getName();
if(name.equals("person")) {
field.set(myObject, new Person());
} else if (name.equals("color")) {
// etc...
}
}
}
I'm, playing with the Android framework and try to get my mind deeper into Java. For This I read about Javas Generics and the Reflection API, while I'm not understanding it really.
Because I'm a lazy Dev ;) I tried to write an 'Parcelable-Container' in which I can put ANY Object I wish to get it Parcelable without the need to implement this for every Object again using methods of Java Reflection.
I write a test method like these:
public <T> void writeClassInformations(T t){
Class c = t.getClass();
System.out.println("DeclaredFields: ");
for (Field f : c.getDeclaredFields()){
System.out.println(f.toGenericString());
}
System.out.println("Fields: ");
for (Field f: c.getFields()){
System.out.println(f.toGenericString());
}
}
How can I get every member even if they are Objects or private Superclass members?
And another Question: The output is like this:
public int hello.test.Testclass.myID
how I get the value of 'myID'?
ADD:
I'm running in serious problems now. The Interface of Parcelable.Creator forces me to write a statement like: public static final Parcelable.Creator CREATOR =
new Parcelable.Creator<ParcelableBox<?>>()
Can I use ? somehow? Normally I use a constructor like ParcelableBox(E object). While it seems to me that I can't use Object methods on ? I even cannot pass it into a class variable like
public ParcelableBox<?> createFromParcel(Parcel source){
...
return new ParcelableBox<?>();
}
or ? myClass to use Reflection on it. Is this the end of javas reflection power? How can I get Class of ?
Reflection should be used sparingly, or not at all if it can be avoided, and especially not as a way to hack around good design principles. That being said, it can also be useful in certain situations ...
getDeclaredFields can return all types of fields while getFields only returns fields marked public.
The reason your test returns the same thing is that you're using getDeclaredFields in both statements.
how I get the value of 'myID'
You can only do that by operating on an instance of a class. E.g.,
T t = ...
Field field = t.getClass().getDeclaredField("myID");
field.setAccessible(true);
String value = (String) field.get(t);
I have a lot of code that calls static methods on Foo like "Foo.method()". I have two different implementations of Foo and would like to use one or the other depending on the circumstances. In psuedocode:
File Foo1.java
class Foo1 implements Foo {
public static int method() {
return 0;
}
}
File Foo2.java
class Foo2 implements Foo {
public static int method() {
return 1;
}
}
File Main.java
if(shouldLoadFoo1()) {
Foo = loadClass("Foo1");
} else {
Foo = loadClass("Foo2");
}
Is this possible with Java metaprogramming? I can't quite wrap my head around all the dynamic class loading documentation. If not, what's the best way to do what I'm trying to do?
Essentially you have two classes with the same interface but different implementations,Wouldn't it be better to do it using an interface?
in your main class, depending on the circumstances you would construct your class with the appropriate instance.
FooInterface foo;
MainClass (FooInteface foo, other fields) {
this.foo = foo;
}
....
then just use foo from them on.
Another way is to use AspectJ, define a point cut on every Foo.method call, in in the advice for the point cut have your if (shouldLoadFoo1()) { Foo1.method()} etc ..
The typical approach to exchanging implementations is to use a non-static method and polymorphism, typically using dependency injection to tell the depedent code the implementation to use.
The next cleanest way is the singleton pattern, i.e. to declare:
public abstract class Foo {
protected abstract void doSomeMethod();
// populated at startup using whatever logic you desire
public static Foo instance;
public static void someMethod() {
instance.doSomeMethod();
}
}
The really hacky way to solve your problem would be what you ask for, i.e. to have two different class files for the same class, and decide at runtime which one to use. To do that, you would seperate your project into 4 different jar files:
loader.jar that determines the classpath to use and constructs the classloader for the actual application. The classes in loader.jar must not reference Foo.
foo1.jar that contains one implementation for Foo
foo2.jar that contains another implementation for Foo
common.jar that contains everything else
Loader.jar would then contain a bootstrap method like:
void bootstrap() {
URL commonUrl = // path to common.jar
URL fooUrl;
if (shouldUseFoo1()) {
fooUrl = // path to Foo1.jar
} else {
fooUrl = // path fo Foo2.jar
}
URL[] urls = {fooUrl, commonUrl};
ClassLoader loader = new UrlClassLoader(urls);
Class<?> mainClass = loader.loadClass("my.main");
mainClass.newInstance(); // start the app by invoking a constructor
}
I am not sure I fully understand the problem here (I see many has that issue), but let me try to help.
If your problem was coming down just to using appropriate function method(), you could create a utility function that depending on an instance of a given class will call appropriate method, e.g.
private static int getResultOfFoo(Foo foo)
{
int res = -1;
if(foo instanceof Foo1)
res = Foo1.method();
else res = Foo2.method();
return res;
}
Otherwise, I agree with Stephen C: "Well, see my answer then. That's the closest you are likely to get in Java."
What you have written doesn't make sense from a linguistic standpoint. Foo is an type, and a type is not a variable and cannot appear on the LHS of an assignment. You cannot treat a type as a value in Java ... the language doesn't allow it.
The closest that you can get to what you are trying to do is something like this:
Class fooClass;
if (loadFoo1) {
fooClass = Class.forName("some.pkg.Foo1");
} else {
fooClass = Class.forName("some.pkg.Foo2");
}
Foo foo = (Foo) fooClass.newInstance(); // using the no-args constructor
(I've left out the exception handling ...)
Note that fooClass will be an instance of the class Class which provides runtime handles that are used for performing operations reflectively. We are NOT actually assigning a type. We are assigning an object that "denotes" a type ... in a limited fashion.
HOWEVER ... if you don't need to use dynamic loading you should not use it. In other words, if the underlying problem that you are trying to solve is creating instances of classes that could be statically loaded, then it is better to use the factory pattern; see #andersoj's answer for example.
UPDATE
I just figured out what you are probably trying to do here. That is, you are trying to figure out a way to choose between different static methods (i.e. Foo1.method() and Foo2.method()) without explicitly naming the classes at the point where the call is made.
Again, what you are trying to do simply won't work in Java:
You cannot declare a static method in an interface.
You cannot call a static method in an implementation class via the interface.
Static method calls are not "dispatched" in Java. They are bound statically.
There is a way to do something roughly like this using reflection; e.g.
Class fooClass;
// Load one or other of the classes as above.
Method m = fooClass.getDeclaredMethod("method");
Integer res = (Integer) m.invoke(null);
(As before, I've left out the exception handling)
Once again you would be much better off doing this without resorting to dynamic loading and reflection. The simple approach would be to create a helper method like this in some utilities class:
public static int method() {
return useFoo1 ? Foo1.method() : Foo2.method();
}
Better still, do it the OO way: declare method in the Foo interface as a instance method, create a singleton or an injected instance of Foo1 or Foo2, and rely on polymorphism.
But the take away is that there is NO WAY to avoid changing all of the places in your codebase where method() is called ... if you want to be able to choose between Foo1.method and Foo2.method at runtime.
You can use a factory pattern to do this.
static Foo makeMeAFoo()
{
final Foo foo;
if(shouldLoadFoo1()) {
foo = new Foo1();
} else {
foo = new Foo2();
}
return foo;
}
Which is I think what you're asking for. Though I like hhafez' suggestion better myself.
(Note my answer is now OBE b/c the questioner shifted the methods to be static rather than instance methods. Nevertheless, the tone of other answerers is good... solving this problem by explicit classloading just because you want to select specific static methods is a kludge.)
In your example you in fact have not two different versions of class Foo, but two different implementations of the interface Foo, which is fine in most cases. (They even can exist parallel to each other.)
It is possible to load multiple classes of the same name, but they have to be loaded by different classloaders. This also means that you can't have a third class referencing it by name and then using one or the other (without the third class also being on two classloaders).
Sometimes it may be sensible to have different versions of a class (with same external interface) for different configurations where it would be used (such as "on client side" / "on server side", when some common class in both modules depends on it), and in rare cases you would have both modules in the same VM at the same time - but in most cases it would be better to use the "one interface and multiple implementing classes" approach instead.
I am reading a Stream, which provides an identifier (a simple int). Depending on the int different data follows, which i need to turn into objects. So far i created classes for each object type, and each class provides a read(InputStream input)-method which reads whatever data there is to be read for that kind of object (all object classes inherit from a common base class).
However, there are numerous id's and thus numerous classes. What is the most elegant way to determine and create the instance of the class?
The most naive approach i tried first was to have a switch-case block to create the instances, but i find that it clutters the code (unreasonably). It also forces me to have every class available at compile time.
Second try was to create a map that maps each int to a class and use newInstance() to create the objects. There is still the problem that i need to initialize the map, which still requires that i have every class available at compile time. It more or less just moved the clutter from one place to another.
Removing the compile time dependencies is not required, it would just be a bonus if possible. The main goal is to avoid the boilerplate code.
Constraints: I don't want to add a library to solve this. Reflection is fine with me.
An alternative approach is to still use a Map but essentially use late-binding, if that's preferable. You could even store the config in a properties file like:
1=java.lang.String
2=my.class.Something
...etc...
You then do something like this:
Map<Integer,ObjectFactory> loader = ... // load from properties; fairly trivial
assuming:
public class ObjectFactory {
private Final String className;
private transient Class clazz;
public ObjectFactory(String className) {
this.className = className;
}
public Object createInstance() {
try {
if (clazz == null) {
clazz = Class.forName(className);
}
return clazz.newInstance();
} catch (Exception e) {
throw new IllegalStateExxception("Could not crate " + className, e);
}
}
}
I think your map solution sounds fine, but move the initial map setup out of of the Java code and into a config file. (Class.forName will help here)
You could have a registry with prototypes.
A prototype of each class you want to be able to create (at a point in time) could be added to your registry object at runtime, these prototypes would each have their own unique integer id.
When you want an object of id x, you just ask of your registry object to clone and return the prototype which id is x. (or null if no such prototype is currently registered).
Internally the registry could be a (hash)map for quick retrieval, but it could just as easily be a list of prototypes (Do make sure of course that all prototypes implement a common interface the registry can work with). Best thing is, no need for reflection!