I'm going through a java codebase and think that it would be much easier to see how the software works if I could temporarily make all fields and methods public.
The access specifiers are basically guidelines to be followed by the programmer while he is coding
(ex. use setter instead of direct assignment to allow the setter to perform some other work associated with the field). Is it possible to tell jvm to ignore the access limiters when running a java program?
Another possibility might be to use some IDE plugin which manually changes the visibility of everything to public
.
What you are asking for won't work on a number of levels.
You can't do this at the source code / compilation level. It alters the Java language. And it wouldn't achieve anything either.
You can't do this in any useful fashion at runtime. You could use reflection to make the fields accessible. However, it is impractical because:
This must be done one Field
at a time, or one Class
at a time; eg
Field[] fields = clazz.getDeclaredFields(); AccessibleObject.setAccessible(fields, true);
You would need to retain all of the Field
objects so "treated", because setting a Field
object to be accessible doesn't affect other Field
objects for the same field.
You could only make use of this if you modified your source code to use reflection and the above Field
objects to access the field values.
If you are trying to understand how your code works, there are other better ways to do it.
@ElliottFrisch Why is it a bad idea?
Basically, because it won't help you.
What you're asking is definitely achievable but raises some questions as to why you might want or need to do it. There is almost always a reason behind setting access modifiers. In fact it may help you to understand the software more if you have a think about why certain fields and methods are made public etc.
I recently started a new job where I had to go through a large codebase and try to understand what everything does. I found that using a Debugger was the best way to step through the code and have a look at the value of each field, variable etc at each point in the program. All good Java IDES have debuggers. I use IntelliJ IDEA which has a very useful debugger that even allows you to run custom evaluation statements at different points in the running of a program.
This is generally considered High Treason by the Style Guide.
Options:
A compiler plugin would probably work, but by the time most programmers get to the point of knowing how, they also know what a bad idea it was. Granted, I am tempted to try now.
Note: I am reasonably sure java's SecurityManager
would take issue with you trying to make it's data public.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.