How do i find interfaces that are anyhow related to the class? - linq

I have an issue, i need to list all the interfaces that are anyhow related to the class? –
For ex:
class Test : interface1
{
public int var1;
classA obj1;
classB obj2;
classC obj3;
}
class classA: interface2
{
testclass obj;
}
class classB: interface3
{
}
class classC: interface4
{
}
class testclass: testinterface
{
myinterface objInterface;
}
interface myinterface{}
My question is how do I list all the interfaces of class Test (it should return all the interfaces anyhow related to the class ex:. interface1, interface2 etc.,).
Anyone help me please?
Thanks in advance

With your current code (almost nothing public, fields instead of properties, etc...), you could do something like that :
var type = typeof(Test);
var interfaces = type.GetInterfaces().ToList();
interfaces.AddRange(type.GetFields(BindingFlags.NonPublic|BindingFlags.Instance)
.SelectMany(x => x.FieldType.GetInterfaces()));
this won't retrieve interfaces of public int var1, as it's... public.
This probably won't fit your exact needs, but without real code and real expected result, it's quite hard to give a better answer.
EDIT
With recursion and your sample, in a console app :
private static void Main()
{
var type = typeof(Test);
var interfaces = type.GetInterfaces().ToList();
GetRecursiveInterfaces(type, ref interfaces);
}
private static IList<Type> GetFieldsType(Type type)
{
return type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Select(m => m.FieldType).ToList();
}
private static void GetRecursiveInterfaces(Type type, ref List<Type> interfaces)
{
foreach (var innerType in GetFieldsType(type))
{
interfaces.AddRange(innerType.IsInterface
? new[] { innerType }
: innerType.GetInterfaces());
GetRecursiveInterfaces(innerType, ref interfaces);
}
}

Related

Should I use dependency injection to bring in a class with constants into my Xamarin Forms application or is there a better way?

I have a class containing constants:
namespace Test.AppService
{
public static class Const
{
public const bool Tmr = false;
public const int Pti = 10;
...
I was wondering if this would be a good candidate for dependency injection or would it be better to leave it as it is and just add using for Test.AppService into every page? Would appreciate advice on this.
Reading your comment about needing to use a different set of constants if that is something you see happening then Dependency injection makes sense. For example if you are using different environments like DEV, QA, Release comes to mind.
You would need to declare an interface with all your public fields. Implement that Interface in different classes with all the possible different scenarios. Then you can register your interface and the class with your desired set of values that you would be able to swap as needed.
For example:
public interface IConfiguration
{
public string ConnectionString {get;}
}
public class QaValues : IConfiguration
{
public string ConnectionString
{ get
{
return "qaconnection";
}
}
}
public class ReleaseValues : IConfiguration
{
public string ConnectionString
{ get
{
return "releaseconnection";
}
}
}
DependencyService.Register<IConfiguration,QaValues>();

Kotlin: Why is defining a field as "var"/"val" needed in constructor?

This is giving an error:
class Apple(weightInGrams: Float){
fun grow() {
weightInGrams+= 2.0f
}
}
First of all, the equivalent of void (in Java) is Unit (in Kotlin), and the type a function returns goes at the end, so you should use fun grow(): Unit { ... } instead of fun void grow() { ... }. Moreover, you can omit Unit and just write fun grow() { ... } because the compiler knows that your function doesn't return any meaningful value.
Now, I'll try to explain the basics to answer your question and give you some clarity. In Java, the parameters of a constructor are visible only inside that constructor. In Kotlin, the parameters are only visible in initializer blocks and in property initializers, unless you transform them into properties. Let's explain all this with examples.
In Java, we see constructors in classes like this many times:
public class Person {
public final String name;
public final Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
}
The parameters are used to initialize the fields of the class Person.
In Kotlin, the equivalent could be:
a) Use the parameters in initializer blocks.
class Person(name: String, age: Int) {
val name: String
val age: Int
init {
this.name = name
this.age = age
}
}
b) Use the parameters in property initializers declared in the class body.
class Person(name: String, age: Int) {
val name = name
val age = age
}
c) Declaring properties and initializing them directly in the primary constructor.
class Person(val name: String, val age: Int)
Therefore, if you write var or val, the parameters of the constructor will be also properties and you will be able to use them in your class like you want to do inside your function grow.
So, your final code should be:
class Apple(var weightInGrams: Float) {
fun grow() {
weightInGrams += 2.0f
}
}
var because you are assigning a value to weightInGrams multiple times.
make your property a class member
class Apple(var weightInGrams: Float){
fun void grow() {
weightInGrams+= 2.0f
}
}
I understand the question was already answered.
If you want to initialize an apple with an initialWeight, you can do it as below. The init block can help initialize the value and the grow function can effectively work on the actual variable without a need to declare the constructor variable as var:
class Apple(initWeight: Float){
var weightInGrams = 0.0f
init {
var weightInGrams = initWeight
}
fun grow() {
weightInGrams+= 2.0f
}
}
fun main(args: Array<String>) {
val a = Apple(10.0f)
a.grow()
println(a.weightInGrams)
};

What does ContainingType mean in java method reference

In Java Method References
ContainingClass::staticMethodName - means that a class can refer the static method (Reference to a Static Method )
containingObject::instanceMethodName - means that a class object is created first and then that object is used to refer the instanceMethod .
My doubt is
ContainingType::methodName - what does the ContainingType mean ?
Is ContainingType a predefined class in java like String or something else ?
Java Language Specification, §4.3. Reference Types and Values:
There are four kinds of reference types: class types (§8.1), interface types (§9.1), type variables (§4.4), and array types (§10.1).
Array type don't have static methods, so that doesn't apply to static method reference, but you can do the other 3:
class MyClass {
static void doIt() {/*doing it*/}
}
interface MyInterface {
static void doIt() {/*doing it*/}
}
class Test<T extends MyClass> {
void test() {
Runnable m1 = MyClass::doIt; // class type
Runnable m2 = MyInterface::doIt; // interface type
Runnable m3 = T::doIt; // type variable
}
}
Now that link is provided in a comment, it says:
Reference to a static method
ContainingClass::staticMethodName
Reference to an instance method of a particular object
containingObject::instanceMethodName
Reference to an instance method of an arbitrary object of a particular type
ContainingType::methodName
Reference to a constructor
ClassName::new
Here, again, ContainingType refers to any of the 3 reference types mentioned above: Class, Interface, and Type Variable.
You can then make a method reference for any instance method of such a type.
class MyClass {
void doIt() {/*doing it*/}
}
interface MyInterface {
void doIt();
}
class Test<T extends MyClass> {
void test() {
Consumer<MyClass> m1 = MyClass::doIt;
Consumer<MyInterface> m2 = MyInterface::doIt;
Consumer<T> m3 = T::doIt;
}
}
https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html
In the document you gave,there is a example of the ContainingType:
String[] stringArray = { "Barbara", "James", "Mary", "John",
"Patricia", "Robert", "Michael", "Linda" };
Arrays.sort(stringArray, String::compareToIgnoreCase);
and explains:
The equivalent lambda expression for the method reference String::compareToIgnoreCase would have the formal parameter list (String a, String b), where a and b are arbitrary names used to better describe this example. The method reference would invoke the method a.compareToIgnoreCase(b).
I think,the element of the stringArray dosen't have a name (eg: String s1 = "Barbara"),so you can't refer it by containingObject::instanceMethodName(eg:s1::compareToIgnoreCase). That's why it uses ContainingType.
I think your ContainingType::methodName is a general/common form of the 2 forms above...
Think about the below code. You can replace the <methodReference> width
InterfaceA::method (for ContainingType::methodName)
ClassA::method (for also ContainingType::methodName)
ClassB::instanceMethod (for ContainingObject::instanceMethodName) or
ClassB::staticMethod (for ContainingClass::staticMethodName)
to demonstrate the mentioned cases:
public class App {
interface InterfaceA {
String method();
}
static class ClassA implements InterfaceA {
public String method() {
return "ContainingType::methodName";
}
}
static class ClassB extends ClassA {
public String instanceMethod() {
return "ContainingObject::instanceMethodName";
}
public static String staticMethod(ClassB classB) {
return "ContainingClass::staticMethodName";
}
}
public static void main(String[] args) {
System.out.println(((Function<ClassB, String>) <methodReference>).apply(new ClassB()));
}
}

Java - Generic class extended by concrete class

I have a number of classes, POJO style, that shares a single functionality, say readCSV method. So I want to use a single parent (or maybe abstract, not sure if it should be) class that these POJOs can extend. Here's a pseudo-code:
(abstract) class CSVUtil {
private String[] fileHeader = null;
protected void setFileHeader(fileHeader) {
this.fileHeader = fileHeader;
}
protected List<WhateverChildClass> readCSV(String fileName) {
// read CSV using Apache Commons CSV
// and return a List of child type
List<WhateverChildClass> list = null;
// some declarations
try {
list = new ArrayList<WhateverChildClass>();
csvParser = new CSVParser(fileReader, csvFormat);
List csvRecords = csvParser.getRecords();
for (...) {
CSVRecord record = (CSVRecord) csvRecords.get(i);
WhateverChildClass childClass = new WhateverChildClass();
// loop through fields of childClass using reflection and assign
for (// all fields of childClass) {
childClass.setWhateverField(record.get(fileHeader[i]));
}
list.add(childClass);
System.out.println(p);
ps.add(p);
}
}
...
return list;
}
}
on one of the child classes, say ChildA
class ChildA extends CSVUtil {
// fields, getters, setters
}
How do I code the CSVUtil such that I can determine in runtime the child class in readCSV defined in the parent class?
Is it possible to make this method static and still be inherited?
As an alternative, is there API in Apache Commons CSV that can generally read a CSV, determine its schema, and wrap it as a generic Object (I don't know if I make sense here), and return a list of whatever that Object is ?
You want that readCSV to be a static method ?
Then, i would say that ChildA class shouldn't inherit from CSVUtil, but implement an Interface ... something like that :
public final class CSVUtil {
private CSVUtil() {
}
public static <T extends ICSV> List<T> readCSV(String filename) {
...
}
class ChildA implements ICSV

How do I make my Entity Framework based Repository Class LINQ friendly?

How can I use LINQ if I have wrapped my Entity Framework data context with a Repository class?
I want to do something like:
class A
{
public IRepositiry<T> GetRepository<T>()
{
DbContextAdapter adapter = new DbContextAdapter(ctx);
return new Repository<T>(adapter);
}
}
class B
{
void DoSomething()
{
A a = new A();
IRepository<House> rep = a.GetRepository<House>();
// Do some linq queries here, don't know how.
rep.[get Linqu] (from ...);
}
}
To keep your repository LINQ friendly you need to have some methods or properties on it that return IQueryable<T> or IEnumerable<T>
So in class Repository<T> you would have a method like this:
public class Repository<T>
{
DbContextAdapter ctx;
// other methods omitted
IEnumerable<Houses> GetHouses()
{
return ctx.Houses
}
}
Then in DoSomething you could do this:
void DoSomething()
{
A a = new A();
IRepository<House> rep = a.GetRepository<House>();
var q = from house in rep.GetHouses()
where house.Color = "Purple"
select house;
foreach(var h in q)
{
house.SetOnFire();
}
}
The standard query operators allow queries to be applied to any
IEnumerable-based information source. - MSDN
As long as you write methods that return IEnumerable Collections you will be compatible with LINQ.
at the risk of been completely lazy, what you want to implement is known as the repository pattern, check out Huyrya as its a good article.
Also it's possible to extend the entity classes, so they return instances or lists of themselves (singleton pattern). Aka:
public partial class FOO : FOO
{
public IEnumerable<Foo> GetFooList()
{
using (var context = new FooEntities())
{
return // YOU CODE TO GET LIST OF FOO
}
}
}
Or something like that (code syntax is not right but should give you the general idea). If your entity classes are going to implement similar methods, abstract them into interface contract and get your partial entity classes to implement that interface.

Resources