How to Get All Class Names Inside a Particular Namespace

How can I get all classes within a namespace?

You will need to do it "backwards"; list all the types in an assembly and then checking the namespace of each type:

using System.Reflection;
private Type[] GetTypesInNamespace(Assembly assembly, string nameSpace)
{
return
assembly.GetTypes()
.Where(t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal))
.ToArray();
}

Example of usage:

Type[] typelist = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "MyNamespace");
for (int i = 0; i < typelist.Length; i++)
{
Console.WriteLine(typelist[i].Name);
}

For anything before .Net 2.0 where Assembly.GetExecutingAssembly() is not available, you will need a small workaround to get the assembly:

Assembly myAssembly = typeof(<Namespace>.<someClass>).GetTypeInfo().Assembly;
Type[] typelist = GetTypesInNamespace(myAssembly, "<Namespace>");
for (int i = 0; i < typelist.Length; i++)
{
Console.WriteLine(typelist[i].Name);
}

Get all classes inside a namespace

As @hawk mentioned, the answer is located here, with sample code that you can use:

Getting all types in a namespace via reflection

PHP, parse all classes of a specific namespace, and list all methods of theses classes

<?php

foreach (glob('src/faa/foo/*.php') as $file)
{
require_once $file;

// get the file name of the current file without the extension
// which is essentially the class name
$class = basename($file, '.php');

if (class_exists($class))
{
$obj = new $class;
foreach(get_class_methods($obj) as $method)
{
echo $method . '\n';
}
}
}

Taken from: Create instances of all classes in a directory with PHP then added get_class_methods usage.

How to get all class names in a namespace in Ruby?

Foo.constants

returns all constants in Foo. This includes, but is not limited to, classnames. If you want only class names, you can use

Foo.constants.select {|c| Foo.const_get(c).is_a? Class}

If you want class and module names, you can use is_a? Module instead of is_a? Class.

How to get all classes in namespace without manually loading the classes?

You could glob the files in a namespaced directory as such:

Dir.glob('/path/to/namespaced/directory/*').collect{|file_path| File.basename(file_path, '.rb').constantize}

So in a Rails initialization file or model you could do:

Dir.glob(File.join(Rails.root, "app", "models", "my_namespace", "*")).collect{|file_path| File.basename(file_path, '.rb').constantize}


Related Topics



Leave a reply



Submit