changing methods access modifires in runtime?

  • Thread starter Ehsan Khoddam mohammadi
  • Start date
E

Ehsan Khoddam mohammadi

Hi, Is it possible to change an access modifire on runtime?
consider this example:

public Class Test {
Test (boolean isPublic,...){
....
if (!isPublic)
//changing someMethod() to public
}
private void someMethod(){
....
}
....

}



thanx
 
D

Daniel Pitts

Ehsan said:
Hi, Is it possible to change an access modifire on runtime?
consider this example:

public Class Test {
Test (boolean isPublic,...){
....
if (!isPublic)
//changing someMethod() to public
}
private void someMethod(){
....
}
....

}



thanx

Not without class instrumentation, and I doubt you *really* want to do
this anyway...
What is the underlying problem you are trying to solve? There are
probable many ways to do what you want.
 
H

Hemal Pandya

Ehsan said:
Hi, Is it possible to change an access modifire on runtime?
consider this example:

Isn't access control only a compile time concept? Say I start with the
following two classes:

class C1 { public static void foo() { System.out.println("C1.foo");} }
class C2 { public static void main(String args[]) { C1.foo(); }}

I compile the two and execute C2. The output is as expected; it prints
"C1.foo". Now, I change C1 as follows:
class C1 { private static void foo() { System.out.println("C1.foo");} }

That is, change the method C1.foo to be private. Now compiling C2 would
give error but executing the previously created C1.class would still
produce the same output.

But I am not sure this works in all cases, the Binary Compatibility
section in JLS seems to say you will get a run time error in certain
cases.

How would you expect this to work? Are you expecting to get a run time
error after restricting access?
 
C

Chris Uppal

Hemal said:
Isn't access control only a compile time concept?

No, the JVM spec also features access control. However, historically the Sun
JVMs have been (bafflingly) lax about runtime checking of access. I think it's
been tightened up in each version of Java, but as of 1.5 it was still possible
to access prviate members via raw bytecode in some cases (but not all, which is
what I find baffling). In 1.5 giving the -Xfuture argument to java.exe would
cause it to implement the required checks (as far as my limited testing could
tell). It may be that 1.6 and/or 1.7 will actually implement the JVM spec
fully by default, but I haven't tried either of them yet.


-- chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top