How to use reflection to call a private method from outside a java class without getting IllegalAccessException?

use setAccessible(true) on your Method object before using its invoke method. import java.lang.reflect.*; class Dummy{ private void foo(){ System.out.println(“hello foo()”); } } class Test{ public static void main(String[] args) throws Exception { Dummy d = new Dummy(); Method m = Dummy.class.getDeclaredMethod(“foo”); //m.invoke(d);// throws java.lang.IllegalAccessException m.setAccessible(true);// Abracadabra m.invoke(d);// now its OK } } If someone is … Read more

What are the differences between the private keyword and private fields in TypeScript?

Private keyword The private keyword in TypeScript is a compile time annotation. It tells the compiler that a property should only be accessible inside that class: class PrivateKeywordClass { private value = 1; } const obj = new PrivateKeywordClass(); obj.value // compiler error: Property ‘value’ is private and only accessible within class ‘PrivateKeywordClass’. However compile … Read more

Why are private virtual methods illegal in C#?

I note that there are two questions here. In the future you might consider posting two questions instead of combining two questions in one. When you combine questions like this often what happens is only the first one gets answered. The first question is “why are private virtual methods illegal in C#?” Here are the … Read more

Is there any way to access private fields of a struct from another package?

There is a way to read unexported members using reflect (in Go < 1.7) func read_foo(f *Foo) { v := reflect.ValueOf(*f) y := v.FieldByName(“y”) fmt.Println(y.Interface()) } However, trying to use y.Set, or otherwise set the field with reflect will result in the code panicking that you’re trying to set an unexported field outside the package. … Read more