I want to find all the default-scoped, aka package-scoped, class members in my project. (Other scopes are no problem, since I can search for the keyword public/protected/private, but there's no keyword to search for in this case.)
Is there an eclipse plugin or anything that can do this kind of search?
public class Foo {
private int a; // these are easy
protected int b; // to find,
public int c; // thanks to keywords
int d; // but ones like this?
}
You might want to look at javap:
http://docs.oracle.com/javase/1.5.0/docs/tooldocs/windows/javap.html
It's primarily intended for disassembling classes, but it also lets you include/exclude class members of different scope (private vs public, for example)
Since javap does not appear to be a suitable solution and I don't know of any suitable plugin, you may have to write your own.
Feed it a list of classes.
for each class
Use Class.forName(className) to get the class object
use getDeclared{Classes,Fields,Methods,Constructors} to get the members.
for each member
Use java.lang.reflect.Modifiers.is{Public,Private,Protected}(member.getModifiers())
It is default if all three are false
If default report that member
You decide whether and how to recurse into inner classes.
I guess that solution will not work for classes nested inside methods. (Neither would javap, javadoc solve classes nested inside methods.) It will make things much simpler if you can just assert that you code does not have classes nested inside methods.
Related
Let's say I have a Java class A, which requires a helper class B. That helper class is only used in A, and has no other purpose. Also, B doesn't need to use A in any way (don't call methods or access fields).
So, the question is: where to put B?
There are the following options:
Static nested class. In my opinion, it just makes code less clear (much more indentation and such).
public class A {
...
private static class B { ... }
}
Non-public class in the same source. I like this option.
public class A {
...
}
class B {
...
}
Non-public class in the separate source. Looks like this option has a little overhead, though.
// A.java
public class A {
...
}
// B.java
class B {
...
}
For now, I prefer the 2nd option. What are your thoughts on it? What is the best practice?
Are there any authoritative sources on it?
I strongly vote for option (1). The idea is, that class B is only needed by class A and option (1) is the only alternative that clearly expresses that intention: class B is part of class A.
You can use a static nested class within A.Better encapsulation since a nested class a way of logically grouping classes that are only used in just one place. does your helper class just contain fields?
was it helpful?
There are no serious disadvantages, but one can certainly figure out at least few including:
Difficult to understand - especially for non-experiences programmers, who may find it difficult to code, enhance, and maintain.
More number of classes - it certainly increases the total number of classes being used by the application. For every class loaded into the memory, JVM creates an object of type Class for it. There may be some other routine tasks, which JVM might be required to do for all the extra classes. This may result in a slightly slower performance if the application is using several nested/inner classes (may be due to a poor design).
Limited support by the Tools/IDE - Nested classes don't enjoy the same support as the top-level classes get in most of the tools and IDEs. This may irritate the developer at times.
Most of the time I define constants in the same class where i want to use them.
But now i have to define all common constants in a separate class. I have seen two version of constants defining classes:
a. It will give compile time error, if you try to create object of Consts.
final class Consts {
private Consts(){}
public static final String TAG = "something";
}
b. If will throw a run time exception, if you try to create a object of Consts.
final class Consts {
public Consts(){
throw new RuntimeException();
}
public static final String TAG = "something";
}
check this class of android http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.2_r1.1/android/Manifest.java
Why they have used second version?
Which one should I use and why should I go for second version?
I don't see any reason for the second version, as the first one (private constructor) does exactly what you want.
Another common idom is to make the constant-holder an interface. However, this is not universally appreciated and can lead to people implement-ing that interface, which is often considered a code smell.
From my point of view, there is no reason to use the second approach. It is misleading from the API since the class exposes a visible constructor that will throw an exception in any case. Clients may fall into that trap.
However, there are other options, too, e.g. you could make Consts an interface
interface Consts {
String TAG = "somthing"
}
This would allow for classes that implement the interface and thereby have "easier" access to the constants (without static imports). Another advantage would be, that you could use find references even if you only have the compiled classes in your IDE. Since the compiler will inline the constants into the using classes, references to TAG are hard to find. If the clients implement that interface, they can be easily lookup up. However, some coding guidline forbid that.
The next option that is possible, would be an enum. The JVM will ensure that there is only one instance for each constant in an enum class:
enum Consts {
TAG, OTHER, ..
}
You can use both, first is simpler and better because causes 'compile' errors, not runtime, i.e. you catch the problem before.
You can also make the class private in the package (not using the public modifier) and write the other classes in the package (if it's always you writing them) so that they don't instantiate that class. Yes, java is OOP, but you don't need to be pedantic. :) I've never seen anybody instantiating a class of static fields by mistake, and if he/she does, than it makes no harm.
I have pairs of classes where the fields of one is a subset of the fields of another and the getters of the superset classes are all predictably named (getFoo()). Is there some way to efficiently copy all the common fields over from the superset class to the subset class, or at least auto-generate the code to do so.
I should note that:
For various reasons, I can't edit the superset classes, nor can I just use them throughout to avoid having to do the data copy.
I can potentially create new methods in the subset classes, but I can't change their fields.
We have dozens of these pairs, and some of the classes have many many fields so doing this by hand is unwieldy to say the least.
A colleague has come up with a method to create a generic copy method that uses java reflection to take any two classes, iterate through the fields as Strings, do string manipulation to determine the getter name, and then execute it to automatically set the field in the subset class. It's awful, but it appears to work. I'm really hoping there's a better way.
Edit: some simple code as requested
public class SuperClass {
private int foo;
private int bar;
private float bat;
public int getFoo() { return foo; }
public int getBar() { return bar; }
public float getBat() { return bat; }
}
public class SubClass {
private int foo;
private float bat;
}
//wanted
public static copySuperFieldsToSubMethod(Object super, Object sub) { ??? }
// also acceptable would be some way to autogenerate all the assignment
// functions needed
You could use the BeanUtils class in the Spring Framework to do this. It may not necessarily be any more efficient than your reflection-based technique, but it's certainly simple to code. I expect that all you would need to do is:
BeanUtils.copyProperties(source, target);
Javadoc for this method is available at http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/BeanUtils.html#copyProperties(java.lang.Object,%20java.lang.Object)
If that doesn't suit, you could also consider using BeanWrapper / BeanWrapperImpl in the Spring Framework to iterate through the properties of your classes. That would be simpler than using low-level reflection APIs.
Similar to the first answer, but to clarify - spring is not needed. Commons BeanUtils.copy properties(Object dest, Object orig)
http://commons.apache.org/beanutils/api/org/apache/commons/beanutils/BeanUtils.html#copyProperties(java.lang.Object,%20java.lang.Object)
If you want to the task efficiently (in terms of runtime performance), then hand coding the copy using getters and setters is the way to go. Unless there is something funky about the getter or setter methods, their bodies will be inlined so that they are as fast as doing field assignments.
The reflective approach (e.g. using an existing class like BeanUtils) is less coding, but probably an order of magnitude slower than calling getters and setters in a simple way. If you try to implement this yourself, you may find yourself with more work than you bargained for, especially if your reflective copy class / method has to cope with overloaded methods, inheritance, value conversion, boxing/unboxing and so on.
With the code generation approach, you need to balance the effort and complexity of implementing the code generation (using whatever technology you choose) versus the effort of writing the copy methods by hand. You probably probably won't break even with the code generation approach before 20 classes ... and many more if you are not familiar with the technology.
To copy based on fields rather than getters and setters, you can use Spring's ReflectionUtils.shallowCopyFieldState().
I'd write a simple java tool to autogenerate the source code for classes that can populate the the subsets fields with the common fields from superset. This tool will use reflection to get the names of the getter and setter methods. The rest are (trivial) String operations to "write" a source file in memory and store it to a *.java file. Compile all this autogenerated files and add the class files to the classpath.
The class could look like this:
class AClassToBClassPopulator implements Populator {
#Overwrite
public void populate(Object superSet, Object subSet) {
subSet.setFieldA(superSet.getFieldA());
subSet.setFieldB(superSet.getFieldB());
// .. and so on. The method body is created through reflection
}
}
Can you provide some sample code from your app that depicts the scenario you have mentioned in your post?
Right now reflection seems like the best way , since it lets you inspect the class members at runtime.
This is obviously a task for Java's reflection and while others have already suggested valid although maybe a bit heavyweight solutions, here's one more:
About a year ago I wrote a smallish JavaBean property modifier library called BeanPropertyController. While I don't specifically recommend it to anyone, I do think that the namesake class of the library (see source) can be used as a reference to adopt similar functionality to your needs. As a quick example, here's how I used BPC to do (almost!) what you're asking:
// somewhere in code...
SuperClass a = new SuperClass();
a.foo = 101;
a.bar = 102;
a.bat = 103f;
SubClass b = new SubClass();
b.foo = 201;
b.bat = 202f;
BeanPropertyController fromB = BeanPropertyController.of(b, ExtractionDepth.QUESTIMATE);
BeanPropertyController toA = BeanPropertyController.of(a, ExtractionDepth.QUESTIMATE);
// This is where the magic happens:
for (String propertyName : fromB.getPropertyNames()) {
toA.mutate(propertyName, fromB.access(propertyName));
}
a = (SuperClass) toA.getObject();
b = (SubClass) fromB.getObject();
System.out.println("SuperClass' foo="+a.foo+" bar="+a.bar+" bat="+a.bat);
System.out.println("SubClass' foo="+b.foo+" bat="+b.bat);
This prints out
SuperClass' foo=201 bar=102 bat=202.0
SubClass' foo=201 bat=202.0
So, what I suggest is that you go to the URL I linked and adapt this piece of code to your needs. I'm quite sure you don't need the various instantiation methods, default value providers etc. which I've included. And yes, BPC can be considered to be deprecated.
I'm using a Java class library that is in many ways incomplete: there are many classes that I feel ought to have additional member functions built in. However, I am unsure of the best practice of adding these member functions.
Lets call the insufficient base class A.
class A
{
public A(/*long arbitrary arguments*/)
{
//...
}
public A(/*long even more arbitrary arguments*/)
{
//...
}
public int func()
{
return 1;
}
}
Ideally, I would like to add a function to A. However, I can't do that. My choice is between:
class B extends A
{
//Implement ALL of A's constructors here
public int reallyUsefulFunction()
{
return func()+1;
}
}
and
class AddedFuncs
{
public static int reallyUsefulFunction(A a)
{
return a.func()+1;
}
}
The way I see it, they both have advantages and disadvantages. The first choice gives a cleaner syntax than the second, and is more logical, but has problems: Let's say I have a third class, C, within the class library.
class C
{
public A func()
{
return new A(/*...*/);
}
}
As I see it, there is no easy way of doing this:
C c;
int useful = c.func().reallyUsefulFunction();
as the type returned by C.func() is an A, not a B, and you can't down-cast.
So what is the best way of adding a member function to a read-only library class?
Natural and frequent dilemma. Read about the composition vs inheritance alternative. Your second alternative is basically a composition, if we think that the object A is passed in the constructor instead of passing it in each method - that is, we would be using composition to implement a wrapper or decorator pattern.
The issue for class C returning a new instance of class A has no trivial solution, as you guessed, as long as class C decides to take responsability of creating the new instance. This is why one should pause and think before typing a "new" statement inside a class, if there is the possibility that this class will be subclassed. In yout example, it would be nice if you could tell class C what concrete class to return ... but how would it know to create it? Well we could pass him an object who knows how to instantiate an object of class A (or a subclass)... I guess you are enough motivated to read about Factories now, and design patterns in general.
There is no unique best answer, but if want a quick one: I'd make a wrapper, B class does not extend A but has a constructor with A as parameter, it delegates its methods (except the own) to the inside object.
When you need to call the method in class C (I'm assuming you cant touch class C), you could write: B b = new B(c.func())
Why not use Composition instead of Inheritance?
class ABetterA {
private A a;
public ABetterA() {
}
// write wrapper methods calling class' A methods and maybe doing something more
}
This way, you could also mimic multiple inheritance...
You have a third option. You could use Scala (a Java compatible language) and its traits, which are mixins by another name.
Another option similar to Brian's sugestion is to use Aspect Oriented Programming (AOP) tool, such as ApectJ, which let you "inject" additional functionality into existing classes, even binary ones. You either preprocess the library jar to get a new one with enhanced classes ("static weaving") or you can do all of this at runtime when the library classes are loaded (so called "load-time weaving"). You can check this AspectJ example.
Even though AOP is normally used to modify existing methods (before, after or around "advices" = code pieces) you can also introduce new members and methods - check AspectJ's Inter-type declarations.
Of course there is the question whether AspectJ is supported at your limited platform.
Is there a way to know the inner classes that a Class has through Reflection in Java?
Yes, use Class#getDeclaredClasses() for this. You only need to determine if it's an inner class or a nested (static) class by checking its modifiers. Assuming that Parent is the parent class, here's a kickoff example:
for (Class<?> cls : Parent.class.getDeclaredClasses()) {
if (!Modifier.isStatic(cls.getModifiers())) {
// This is an inner class. Do your thing here.
} else {
// This is a nested class. Not sure if you're interested in this.
}
}
Note: this only doesn't cover anonymous classes, but seeing your previous question on the subject, I don't think you're explicitly asking for them.
No, unfortunately, for the same reason why you cannot enumerate regular classes in a package.
Inner classes are really just ordinary classes at runtime. The compiler does some tweaking to get around the usual access rules, For example, the inner class appears to be able to access private fields and methods of the enclosing class - it can do this because the compiler creates a non-private accessor function that is used by the inner class. See Java in a Nutshell - how inner classes work for details.
Inner classes are regular classes, and these can't be reliably enumerated, so the general answer is no, not possible.
However, it can be solved in specific cases. If you know the JARs you are using, then you can iterate across all files in the JAR, looking for files of the pattern yourpakage.YourClass$<something>.class where <something> is one or more characters.
EDIT:
There are various types of inner class:
declared members, such as interfaces and classes
Anonymous classes and local classes
If you only care about the first case, then BalusC's answer using getDeclaredClasses is the correct one. If you want all inner classes, then getDeclaredClasses unfortunately won't work. See SDN Bug 4191731. In that case, you might try one of the class enumeation methods proposed in the link (such as scanning the JAR file.)
Yes, there is a trick to do that. See an old post about locating resources. Knowing your class(let's say com.domain.api.ClassA), extract the package name, convert the package to a path(replace '.' with '/' and you get com/domain/api) scan for all the files with extension .class in that folder and retain only those files which starts with your class name(ClassA$xxxxx), those are the inner classes for class ClassA