Why is there no concurrency with Java setAccessible in .NET?

Take a look at setAccessible , a way in Java, so you can call private methods reflections. Why didn’t .NET implement such a function?

+3
source share
4 answers

Here is an example of this in .NET

using System;
using System.Reflection;
using System.Collections.Generic;

public class MyClass
{
   public static void Main()
   {
        try
        {
            Console.WriteLine("TestReflect started.");
            TestReflect test = new TestReflect();
            Console.WriteLine("TestReflect ended.");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

        ConsoleKeyInfo cki;
        do
        {
            Console.WriteLine("Press the 'Q' key to exit.");
            cki = Console.ReadKey(true);
        } while (cki.Key != ConsoleKey.Q);
   }
}

public class TestReflect
{
   public TestReflect()
   {
        this.GetType().GetMethod("PublicMethod").Invoke(this, null);
        this.GetType().GetMethod("PrivateMethod", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(this, null);
   }

   public void PublicMethod()
   {
        Console.WriteLine("PublicMethod called");
   }

   private void PrivateMethod()
   {
        Console.WriteLine("FTW!one1");
   }
 }
+5
source

You can use reflection to call private methods, although this is not as straightforward as calling public methods. We did this earlier for unit testing and used the following entries as reference information:

http://www.emadibrahim.com/2008/07/09/unit-test-private-methods-in-visual-studio/

http://johnhann.blogspot.com/2007/04/unit-testing-private-methods.html

+4

.NET - , .

, , Foo on bar, :

typeof(Bar).GetMethod("Foo",BindingFlags.NonPublic | BindingFlags.Instance);

, .

(Security requirements for V4 will be different)

+2
source

Source: https://habr.com/ru/post/1710022/


All Articles